Note: This is the first installment of our new series Know Your ORM. Stay tuned for more.
So, you have been learning Django since a few days or weeks. You have worked with Django ORM and Django QuerySet API. And, you are totally familiar with this line.
objs = Model.objects.all()
But, ever wondered where do
objects come from?
So basically, Django has a thing called Manager . It handles all the operations among and between models. Look at the snippet below:
# First define a Manager subclass class PublishedManager(models.Manager): ''' Manager to return only the blogs which are published ''' # You can also override other methods if you like. def get_queryset(self): return super().get_queryset().filter(is_published=True) class Blog(models.Model): title = models.CharField(max_length=70) author = models.CharField(max_length=60) body = models.TextField() is_published = models.BooleanField(default=False) objects = models.Manager() # Default Manager [so you do objects.all(),get(), etc] # You can also override default manager if required. published = PublishedManager() # This is how you hook [Blog.published.all(), get(), etc]
Considering the above snippet, when you call
Blog.objects.all() it calls the default Model Manager and everything works fine. But, when you call
Blog.published.all(), it only returns the blogs which are published i.e. (
This was just one simple use case but I am sure this opens up a bigger opportunity of making Django QuerySet API more flexible.
If you have any queries and questions regarding Django, you can post in comment section below.