Custom Model Managers In Django
A manager is an interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application, objects is the default manager of every model that retrieves all objects in the database.
However, one model can have multiple model managers, we can also build our own custom model managers by extending the base manager class.
Creating Custom Model Managers
`class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
active = models.BooleanField(default=False)
def __str__(self):
return self.title`
objects is the default model manager for every model, therefore Post.objects.all() will return all post objects.
The objects method is capable of doing all basic **QuerySets **then why would we need a custom model manager?
Why would we need Custom Model Manager
To add extra Manager methods.
To modify the initial QuerySet the Manager returns.
Let’s create a model manager to retrieve all the published posts.
Using the objects manager published posts can be retrieved with the following query.
Lets create some dummy data using Django Shell,
>> Post.objects.filter(active=True) Out: <QuerySet [<Post: Fourth Post>, <Post: First post>]>
>> <QuerySet [<Post: Fourth Post>, <Post: First post>]>
We will build a custom model manager called publish to retrieve the published posts.
class PublishManager(models.Manager):
def get_queryset(self):
return super(PublishManager, self).get_queryset().filter(active=True)
class Post(models.Model):
.. our fields
objects = models.Manager() # The default manager.
publish = PublishManager() # Our custom manager.
def __str__(self):
return self.title
Now we can retrieve posts with the custom model manager as follows.
>> Post.published.all()
>> <QuerySet [<Post: First post>, <Post: Fourth Post>]>
>> Post.objects.filter(active= True)
>> <QuerySet [<Post: First post>, <Post: Fourth Post>]>
Hope this would help you to understand the basic idea about custom model manager.
Top comments (0)