I would like to know how do managers work in Django. Let’s use the following example (from The Definitive Guide to Django) as the model:
class BookManager(models.Manager):
def title_count(self, keyword):
return self.filter(title__icontains=keyword).count()
class Book(models.Model):
title = models.CharField()
...
objects = BookManager()
Given that model, we can use Book.objects.title_count('django'). However, I’m not sure about what’s going on in the background. When we use title_count, self refers to the instance BookManager, which knows about a method called filter because it’s inheriting such a method from the models.Manager class, but how does it know that it should use filter in instances produced by the Book class?.
I would naively think that title_count needs to do Books.objects.filter(title__icontains=keyword).count() internally but it’s using explicitly something like objects.filter(title__icontains=keyword).count() without referring to a particular class.
from the source code it looks like the manager class has a reference to the model that it is embedded in to: https://code.djangoproject.com/browser/django/trunk/django/db/models/manager.py#L106