Built in & Custom Model Managers in Django
Last Updated :
18 May, 2021
Django manager is a class that acts as an interface through which Django models interact with databases. Every model has at least one manager object. It has a lot of methods, attributes to ease working with databases. In fact, many beginner-level Django developers do not know that they use the Manager class object to extract or create desired model object/objects. The default Manager object that Django provides in models is "objects".
Syntax :
To use the Django default manager object, you have to follow the below syntax -
model_name.objects.method
Here "objects" is the manager object that Django creates by default.
One basic example :
Let's say we have a model class named Hospital -
class Hospital(models.Model):
name = models.CharField(max_length=50)
city = models.CharField(max_length=30)
def __str__(self):
return self.name
But it did not create any objects in the database yet. It only creates an empty table with the structure of hospital objects. To create these objects in the database we need to use our default Django manager object (As we have not to build any custom manager) -
Hospital.objects.create(name='AIIMS',city ='Delhi')
The 'create' method creates a new object. It takes field values that the model class wants. In the above code line, we created a hospital object by calling the 'create' method which takes field values as an argument.
Giving a custom name to the default manager :
Sometimes there is a need to give a custom name to the default manager. To do this you have to define a class attribute or field of type models.Manager(). Here is an example -
class Student(models.Model):
...
students = models.Manager() //now the default manager is named as students
After this, all the operation on the student database table have to be done using the "students" manager -
Student.students.filter(...) // here students manager is used
Any effort of using "objects" as manager for this class will lead to giving an error.
Methods of Manager class :
Manager objects have many in-build methods to ease the operations on the database. Some of the most popular methods are described here -
all() | returns a query set containing all objects created so far |
filter(**kwargs) | returns a query set containing a list of objects that match with the given arguments. If no matched object is found, it returns an empty query set. |
exclude(**kwargs) | it does exactly the opposite of filter() method i.e. returns a queryset containing objects that does not match with given arguments. |
get(**kwargs) | returns a single object that match with given argument. If multiple objects found it will throw an Model.MultipleObjectsReturned error. If get() doesn’t find any object, it raises a Model.DoesNotExist exception. |
create(**kwargs) | create a new object with given arguments. |
order_by(*fields) | sets the ordering of the previously returned queryset according to the arguments passed in it. |
Example :
This following example uses python command shell.
>>> h1 = Hospital.objects.create(name="Calcutta Medical",city="kolkata")
>>> h2 = Hospital.objects.create(name="dummy",city="Chennai") #creating objects using create() and save all these new objects into database
>>> h3 = Hospital.objects.create(name="TATA cancer Hospital",city="Mumbai")
>>> h4 = Hospital.objects.create(name="AIIMS Delhi",city="Delhi")
>>> h5 = Hospital.objects.create(name='NRS hospital",city="kolkata")
...
>>> Hospital.objects.filter(city='kolkata') # returns queryset of objects whose city attribute is 'kolkata'
<QuerySet [<Hospital: Calcutta Medical>, <Hospital: NRS hospital>]>
>>> Hospital.objects.get(city='Delhi')
<Hospital: AIIMS Delhi>
>>> Hospital.objects.get(city='kolkata') # raise error as there are multiple objects
These are the most popular methods . However the number of such methods are huge. You can check django documentation for complete reference.
Creating custom managers :
Sometimes you may want django manager to work in a certain way which default manager don't. In that case you can make your own custom managers. The procedure is easy. You have to make a class which inherits from Manager class. Here is an example -
Example :
Let's talk about Hospital model. We are creating a custom manager called CustomManager which is similar to the default django manager except one thing. When we call all() method of CustomManager object we will not get all objects. Instead we will get all those objects that have city = 'kolkata' -
Python3
class CustomManager(models.Manager):
'''first we get all objects from the database by
calling the get_queryset method of the inherited class
i.e. Manager class using super().get_queryset().
After that we are filtering objects having city attribute equal to kolkata
and return the filtered objects'''
get_queryset(self):
return super().get_queryset().filter(city= 'kolkata')
Every manager class have a get_queryset method. It is used to get queryset of objects based on the properties it takes as arguments. If no argument is provided then it will return all the objects. In this example, we create a custom django manager by inheriting Manager class and overriding only the get_queryset method .
So we have defined a custom manager . Now all we have to do is we have to link this manager with Hospital model -
Python3
class Hospital(models.Model):
name = models.CharField(max_length=50)
city = models.CharField(max_length=30)
objects = models.Manager() # our default django manager
kolkata_hospitals = CustomManager() # creating our custom manager object
def __str__(self):
return self.name
Hospital model have two manager objects. Now if we call Hospital.objects.all() , we get all the hospital objects. But when we call Hospital.kolkata_hospitals.all() we will get only those objects whose city is kolkata.
Note that if you are using multiple manager objects in same model then you need to be careful about the order of the manager objects defined. The first defined manager object will be treated as default manager object. For example - In above example, "objects" is the default manager as it is defined first. Django uses default managers in some internal process. So, be careful about choosing your default manager or you may get some unexpected results. If you want to make a manager default and that manager object is not defined first then you can define it as default manager by setting default_manager_name of Meta class equal to that object name.
class Hospital(models.Models):
...
class Meta:
default_manager_name = 'kolkata_hospitals' # default manager is now kolkata_hospitals not objects
You can do anything you want with custom managers. You can define a new method to modify some data in database, or return something. It is not necessary that every manager method should return a queryset. In fact you can define methods that return nothing.
If you want to know more , checkout Django's official documentation on manager - https://docs.djangoproject.com/en/3.0/topics/db/managers/
Similar Reads
Custom Django Management Commands
Prerequisites:Â Django Introduction and Installation Manage.py in Django is a command-line utility that works similar to the django-admin command. The difference is that it points towards the project's settings.py file. This manage.py utility provides various commands that you must have while workin
4 min read
Customizing Phone Number Authentication in Django
As we know, Introducing phone number-based authentication in the Django Admin Panel is a strategic move to modernize and enhance your web application's security. In the traditional Django authentication system, users use a unique username and password to access their accounts. However, in today's di
3 min read
Customize Django Admin Interface
Django admin by default is highly responsive GUI, which offers various features and an overall CRUD application to help developers and users. Moreover, Django admin can be customized to fulfill one's needs such as showing fields on the home page of the table, etc. In this article, we will discuss ho
3 min read
Django App Model - Python manage.py makemigrations command
According to documentation, Migrations are Djangoâs way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. Theyâre designed to be mostly automatic, but youâll need to know when to make migrations, when to run them, and the common proble
2 min read
Render Model in Django Admin Interface
Rendering model in admin refers to adding the model to the admin interface so that data can be manipulated easily using admin interface. Django's ORM provides a predefined admin interface that can be used to manipulate data by performing operations such as INSERT, SEARCH, SELECT, CREATE, etc. as in
3 min read
Meta Class in Models - Django
Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D
3 min read
How to Add a Custom Field in ModelSerializer in Django
A key component of Django Rest Framework (DRF) is the Serializer, which converts complex data types like Django models into JSON, XML, or other content types. The ModelSerializer, a subclass of Serializer, automatically creates fields based on the modelâs fields, significantly reducing boilerplate c
4 min read
Django Basic App Model - Makemigrations and Migrate
Django's Object-Relational Mapping (ORM) simplifies database interactions by mapping Python objects to database tables. One of the key features of Django's ORM is migrations, which allow you to manage changes to the database schema.What are Migrations in Django?Migrations are files that store instru
4 min read
Creating custom user model API extending AbstractUser in Django
Every new Django project should use a custom user model. The official Django documentation says it is âhighly recommendedâ but Iâll go a step further and say without hesitation: You are straight up crazy not to use a custom user model up front. Why do u need a custom user model in Django? When you s
4 min read
default - Django Built-in Field Validation
Built-in Field Validations in Django models are the validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. defau
3 min read