Django Blog #13: Creating Model Managers

by Alex
Django Blog #13: Creating Model Managers

As mentioned, objects is the default manager for each model. It gets the objects from the database. But you can define your own managers for models. Let’s try to create our own manager to get posts with published status. You can add them in two ways: by adding additional manager methods or by modifying the original ones. The first provides QuerySet APIs such as Post.objects.my_manager() and the second provides Post.my_manager.all(). The manager will allow you to fetch posts using Post.published.all(). Edit the models.py file of the blog application to add a custom manager:

class PublishedManager(models.Manager) 
def get_queryset(self)
       return super(PublishedManager,  
self).get_queryset()
                         .filter(status='published')

class Post(models.Model) 
   # ...
    objects = models.Manager() # Default manager  
    published = PublishedManager() # Own manager

The manager’s get_queryset() method returns a QuerySet, which will be executed. Let’s rewrite it to include the custom filter in the final QuerySet. The custom manager has already been defined and added to the Post model; it can now be used to execute queries as well. Let’s check. Start the development server with this command:

python manage.py shell

You can now retrieve all posts whose names begin with Who:

Post.published.filter(title__startswith='Who')

Related Posts

LEAVE A COMMENT