Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding get() method in models

Am trying to override get() method in my view as :

broadcast = Broadcast.objects.get(request, pk = broadcast_id) 

In my model am overriding method as :

class Broadcast(models.Model):      
    person = models.ForeignKey(User)
    post = models.CharField(max_length=300 , verbose_name = 'Say it out loud !')
    .
    .

    def get(self, *args, **kwargs):
        if request.user == self.person :
            super(Broadcast, self).get(*args, **kwargs)
        else :
            return none

Two questions ->
Where am I going wrong with the overriding?
How do I access the "request" argument passed into get?

like image 496
D_D Avatar asked Jun 29 '11 12:06

D_D


2 Answers

Given the poll app example in the Django tutorial. You can perform a get operation to fetch poll questions from the database.

In : Question.objects.get(pk=1)
Out: <Question: Question object>

This blog post shows how to override that method. It is not on the model itself. Question.objects gives you the manager.

In : Question.objects
Out: <django.db.models.manager.Manager at 0x10d3b8860>

You can drop in a custom manager in your models.py.

class QuestionManager(models.Manager):
    pass

class Question(models.Model):
    objects = QuestionManager()

which results in...

In : Question.objects
Out: <app.models.QuestionManager at 0x107456e48>

But we are not quite there yet. Question.objects.get is doing some delegation magic and actually calling get on an instance of QuerySet. We can replace

class QuestionQuerySet(models.query.QuerySet):
    def get(self, **kwargs):
        print('hello world')
        return super().get(**kwargs)

class QuestionManager(models.Manager.from_queryset(QuestionQuerySet)):
    pass

Voilà!

In : Question.objects.get(pk=1)
hello world
Out: <Question: Question object>

References:

  • https://docs.djangoproject.com/en/1.10/topics/db/managers/#from-queryset
  • https://docs.djangoproject.com/en/1.10/ref/models/querysets/#get
like image 146
Brian Edwards Avatar answered Oct 12 '22 00:10

Brian Edwards


get isn't a method on the model - you access it via objects, so it's a method on the Manager. See the official Manager documentation.

The way you have defined the method signature, the request is available as args[0].

like image 25
Daniel Roseman Avatar answered Oct 11 '22 22:10

Daniel Roseman