Creating model managers

As we previously mentioned, objects is the default manager of every model that retrieves all objects in the database. However, we can also define custom managers for our models. We will create a custom manager to retrieve all posts with the published status.

There are two ways to add managers to your models: you can add extra manager methods or modify initial manager QuerySets. The first method provides you with a QuerySet API such as  Post.objects.my_manager(), and the latter provides you with Post.my_manager.all(). The manager will allow us to retrieve posts using Post.published.all().

Edit the models.py file of your blog application to add the custom manager:

class PublishedManager(models.Manager): def get_queryset(self): ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.