Manager & QuerySet in Django Models

Learn via video courses
Topics Covered

Overview

A Manager is a Django class that acts as a bridge between database queries and Django models. Every model in a Django application has at least one Manager. Django managers enable us to get the records from the model using the manager methods.

Introduction

A Django model is a built-in feature of Django that allows you to create tables, fields, and constraints. In general, each model corresponds to a single database table. It organizes tables into models and simplifies tasks. A model's fundamentals include:

  • Each model is a Python subclass of django.db.models.Model.
  • Each model attribute represents a database field.
  • Django provides you with an automatically generated database-access API.

Let us consider an example, of a model.

  • We have created a class SampleModel.
  • We created fields such as title, description, and contact_no.
  • In the field title, we created a character field using .CharField().
  • In the field description, we created a text field using .TextField().
  • In the field contact_no, we created an integer field using .IntegerField().
  • def str(self) makes sure that the model returns the particular field selected in the return statement when a record is called. In our case, when the record is called in the query set it returns the title of the record.

After creating the model, we register it in the admin.py file,

Django Manager

A Manager is a Django class that acts as a bridge between database queries and Django models. In other words, the manager is the interface that interacts with the database in a Django model. For example, if you want to retrieve objects from your database, you must create a QuerySet on your model class using a Manager.

Syntax of Django Manager

To use the default Django manager object, use the syntax below.

Say we have model details, including name, description, contact_no, and age.

With this we just created a table without records, we used the 'create' method to add data to it.

Methods of Manager Class

Apart from the 'create' method for creating the records, there are some other methods also for performing other queries.

MethodsDescription
all()returns a query set containing all objects created.
filter()returns a query set with a list of objects that match the given arguments.
get()returns a single object that corresponds to the given argument.
create()creates a new object.
order_by()returns the query arranged in a particular order as mentioned in the argument.

Custom Manager Class

Django manager works as an interface between the queries and the model. Django provides us with a feature of customizing the Django manager to work accordingly. Let us consider we have model details and when we use the all() method, the manager returns all the records but we want the manager to return the list of records where the age is 20 only. Therefore we create a custom manager in the models.py file, then link it to the model details.

In the above code,

  • We have created a class MyCustomManager.
  • Under the function get_queryset, we return super().get_queryset().filter(age= '20') so that we get all the records where the age is 20.

Now in the model details, we link it.

  • In the field detail_20, we linked the manager we created.

Django QuerySet

A Query Set is a collection of data from a database. Query set allows us to get data easily, by allowing us to filter, create, order, etc.

Syntax of QuerySet

Let us consider an example.

In the above code, we created two models Album and Song. Whenever an instance of a model is created in Django, it will display the object as Modelname Object(1) in the admin interface. Hence to change the display name we use the function def str(self). The Str function in a Django model returns a string that is rendered as the display name of instances for that model.

In our case, it will display the name of the title for the Model Album and the name of the song for the Model Song. In the Model Song, we are linking the second field, the album with the Model Album.

Register the model in the admin.py file,

After creating and registering the models, we need to use the following command:

In the above commands,makemigrations is responsible for packing up the changes into individual migration files, and migrate is responsible for applying those to our database.

Now we need to access Django ORM, it can be accessed by using the following command inside our project directory:

This leads us to an interactive console. Next, we are supposed to import our models using the following command:

Let us now see the working of the query set.

  • Add Objects

We write the following code to create and save an object of Model Album:

We write the following code to create and save an object of Model Song:

  • Retrieve objects

Retrieving stands for getting the result of the search we make. So for retrieving the data in Django, let us add some records for ease of explanation.

To retrieve all the objects of a model,all() is used:

The output is a set of objects that match the query. Since we used the str() function for the model Album we see the output has the title displayed for all the objects.

  1. The filter() is used to retrieve the data that exists already based on the condition we give in the command. For example, in the code below we used to filter(artist="Imagine Dragon") so the query set returned shows the list of albums with the artist name as "Imagine Dragon".
  1. The exclude() is used to retrieve the objects excluding or omitting the conditions we give in the command. In the code below we used,exclude(artist= "Imagine Dragon") and the output it returns does not contain any album with the artist name "Imagine Dragon".
  1. The get() is used to retrieve a single object matching the conditions we give in the command. In the code below, we used the command get(pk = 3), pk stands for the primary key. It uniquely identifies each row in the table. So here pk=3 returns the third object of the model. Django documentation declares that the primary key can be accessed using the keyword pk.
  • Modify existing objects

Django also allows us to modify existing objects. At first, we use get() to retrieve the single object which we want to modify then enter the data as in the code below a.artist="One Direction" and save it using "a.save()".

  • Delete Objects

To delete a single object, at first we use get() function then delete():

To delete multiple objects, we can use filter() or exclude():

Difference between Manager and QuerySet

A manager is an interface between the model and the queries we make. Manager enables us to make queries with the help of its methods. QuerySet is the list of records we get as output after making the queries.

Conclusion

Hello Developer!! I am sure by now you must have learned what Django managers and QuerySets are. Let us summarize what we have learned so far

  • A Manager is a Django class that acts as a bridge between database queries and Django models.
  • A Django model is a built-in feature of Django that allows you to create tables, fields, and constraints.
  • The manager is the interface that interacts with the database in a Django model.
  • Query set allows us to get data easily, by allowing us to filter, create, order, etc.