Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model Manager in Django - No reference to model class?

I'm having a hard time understanding how works a modelManager in Django 1.6.

I don't understand where is the magic that makes this code work.

In the get_queryset(self) method there is no reference whatsoever to the Book class, so how come the DahlBookManager knows that it needs to work with the Book instances when doing super(DahlBookManager, self) (no reference to Book model, and as far as I know, self refers to an object of type "DahlBookManager" and not Book).

So either there is some kind of magic, or I REALLY need to review my Python 101. I'd be happy to have some help, thanks!

# First, define the Manager subclass.
class DahlBookManager(models.Manager):
    def get_queryset(self):
        return super(DahlBookManager, self).get_queryset().filter(author='Roald Dahl')

# Then hook it into the Book model explicitly.
class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=50)

    objects = models.Manager() # The default manager.
    dahl_objects = DahlBookManager() # The Dahl-specific manager.
like image 819
jhagege Avatar asked Sep 17 '25 12:09

jhagege


1 Answers

When you create a model class in django, it calls add_to_class for each attribute on the model.

https://github.com/django/django/blob/1.6.5/django/db/models/base.py#L143

if what you're trying to add the class has a contribute_to_class method, then it gets called instead of calling setattr

https://github.com/django/django/blob/1.6.5/django/db/models/base.py#L264

So when you assign the manager to the model class with

dahl_object = DahlBookManager()

contribute_to_class() is called on the manager class, which receives the model class. It saves this on self.model:

https://github.com/django/django/blob/1.6/django/db/models/manager.py#L69

get_queryset() then uses this reference to self.model:

https://github.com/django/django/blob/1.6/django/db/models/manager.py#L123

like image 159
Stuart Leigh Avatar answered Sep 19 '25 04:09

Stuart Leigh