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 Installation

Django Installation Django development environment consists of installing and setting up Python, Django, and a Database System since Django deals with a web application. Below the statement will guide you through installing Python 3.8.0 and...

2 minutes read.

Best Django courses

In this tutorial, we will see various courses in python Django available on the internet. Django has become popular these days, so courses on it are also increasing day by...

7 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 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 Environment Setup

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. A framework is a collection of...

4 minutes read.

Django and React

This article will discuss the overview of Django and React, their advantages, applications, and most importantly, how to implement react in Django. What is Django? Django is a free and open-source web...

6 minutes read.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 minutes read.

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 Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

3 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 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 CMS vs WordPress

Both Django CMS and WordPress belong "Self-Hosted Blogging" or "Content Management System (CMS)" category, that is used to manage digital content. Bloggers usually use these platforms. Django CMS Django is one of...

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

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 minutes read.

Django Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

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

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 Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

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.