Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information and data.

To retrieve the information from many relational and non-relational databases, a query is written. But Django provides a handy and powerful tool called Django Object Relational Mapper, which is also known as Django ORM.

Django ORM communicates between the relational database and the user application. Django ORM is used to retrieve or query records from databases like SQL.

One of the advantages of Django ORM is that it makes queries or fetches the data, and the programmer does not have to write the query in SQL, which can be very complicated and hard to understand at times. The main features of Django ORM are:

  • With the help of Django ORM, the development is relatively quick.
  • It is easier to change the database from ORM.
  • The programmer does not have to learn different SQL for all the databases.

Query Set

A queryset is a list of objects in the model. By Query sets, we can retrieve and update the data from the database. We can perform operations in Queryset without actually hitting the database.

Demonstration

Now to demonstrate the Django filter method, we will create a model first and then will pass different methods to filter the data from the database.

We will take look at this model:

fromdjango.dbimportmodels
classAccount(models.Model):
username=models.CharField(max_length=200)
email=models.EmailField()




def__str__(self):
returnself.username


classPost(models.Model):
name=models.CharField(max_length=100)
caption=models.TextField()
    Author = models. ForeignKey(
Account,
on_delete=models.CASCADE,
related_name=’username’
    )




def__str__(self):
returnself.name

We have created two fields here, Account and Post, and each Account has multiple posts associated with it. The fields in Account are the username of the person and the email id used for that Account. The fields assigned to Post are the name of the Post given by the server, the caption for that Post, and the author who made this Post. The username and the author are in one too many relationships.

To access the Django ORM run the following command in the project library.

Python manage.py shell.

Creating Object

To filter any data, it is necessary to create some data. So, first, we will create some objects in our model.

>>>fromapp.modelsimport*
>>>a=Account(username='Javatpoint',email='[email protected]')
>>>a.save()

This is an insert SQL statement in terms of SQL. The object will not get stored in the database until we save the object by calling save(). The save() method does not return anything. We will create some more objects for demonstration purposes.

Obj = Account(username = “Robert”, email = [email protected])
Obj.save()
Obj1 = Post(name = “post1”, caption = “New Article Out”, author = “Robert”)
Obj1.save
Obj2 = Post(name = “post2”, caption = “Django Overview”, author = “Robert”)
Obj2.save
Obj3 = Post(name = “post3”, caption = “Website for all”, author = “javatpoint”)
Obj3.save

Filtering Objects

If we retrieve objects by the all() method, we will get all the objects in the database. But in many cases, we will need only some objects based on s filter. To get these objects, ORM provides a filter method () which is used to retrieve a Queryset with only filtered objects in it.

Syntax:

filter(**kwargs)

returns a new Queryset with objects that matches the filter condition.

For example:

Account.objects.filter(email = “[email protected]”)
<QuerySet[<Account: Javatpoint>]>

Every time we filter a queryset, we get a new Queryset that is in no way related to the old ones. Each filtration creates a new Queryset that can be stored and used. The ct of creating and refinement of Queryset does not affect the database. Querysets can be chained to do complex queries.