Creating Model Managers in Django
Model Managers:
- object is the default manager of every model that retrieves all objects in the database.
- We can also define custom managers for your models.
- We will create a custom manager to retrieve all posts with the published status.
- There are 2 ways to add or customize managers for your models: you can add extra manager methods to an existing manager, or create a new manager by modifying the initial QuerySet that the manager returns.
- The first method provides you with a QuerySet API such as Posts.objects.my_manager()
- The 2nd method provides you with Posts.my_manager.all().
- The manager will allow you to retrieve posts using Posts.published.all().
- Edit the models.py file of your <<xx>> application to add the custom manager:
class xxManager(models.Manager):
def get_queryset(self):
return super(xxManager,
self).get_queryset().filter(status='published')
class Posts(models.Model):
objects = models.Manager() # The Default Manager.
published = xxManager() # The Custom Manager.
- The 1st manager declared in a model becomes the Default Manager. You can use the Meta attribute default_manager_name to specify a different default manager.
- If no manager is defined in the model, Django automatically creates the objects default manager for it.
- If you declare any managers for your model but you want to keep the objects manager as well, you have to add it explicitly to your model.
- In the above code, you add the Default Objects Manager and the Published Custom Manager(xxManager()) to the Post model.
- The get_queryset() method of a manager returns the QuerySet that will be executed.
- We can override get_queryset() method to include your custom filter in the final QuerySet.
- We have now defined the Custom Manager and added it to the Posts model;
- from blog.models import Posts
- Posts.published.filter(title__startswith='abc')
- To obtain results for this QuerySet, make sure that you set the published field to True in the Posts object whose title starts with abc.
Comments
Post a Comment