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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With