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='Javatpoint@jtp.com')
>>>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 = robert@gmail.com)
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 = “jtp@gmail.com”)
<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.


Related Topics

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.

Django Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 minutes read.

Django Logging

Every application developed has some bugs and errors. It is the responsibility of the developers to maintain the application by making it bug-free and error-free. To debug the application code...

5 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Django Create Superuser

For managing the website, we need an Admin while creating the Django application. In order to create the admin user, create superuser command is used. The superuser is called the...

3 minutes read.

Django Create App

Django is a Python-based web framework that is based on the Model View Template architecture. In this post, we will go through the installation and setup for our first Django...

4 minutes read.

Django Model

Django Model A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are...

6 minutes read.

Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website,...

3 minutes read.

Django Celery

Django is a python-based web framework. It is an open-source and free-to-use framework. Django uses the Model View Template architecture. Django provides many functionalities to web developers. One of these...

3 minutes read.

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...

3 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

Django Frontend

Django Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the front...

3 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Django Tutorial

Django Introduction It is a web application framework written in a python programming language. It based on the MVT( Model View Templet) design pattern. It takes a short time to build an application...

2 minutes read.

Django All Auth

For any web application, user registration and authentication are the essential parts. In Django, there are several applications like django-registration-redux to perform these tasks, but the major drawback is that...

6 minutes read.

Django ORM

Django is a Python web framework that enables easy and quick web development. Django has a handy and powerful feature called Django Object Relational Mapper, also known as Django ORM,...

3 minutes read.

Django DRF

Django Rest Framework, which is also referred to as DRF, is a very powerful application to build RESTful APIs in a Django application. DRF uses the Django framework. Similar to...

3 minutes read.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.