Python Django filter

In this Django Tutorial, we will discuss “Python Django filter” and we will also discuss different examples related to filters in Django. And we are going to cover the following topics in this tutorial.

  • Python Django filter
  • Python Django filter or
  • Python Django filter and
  • Python Django filter in
  • Python Django filter not equal
  • Python Django filter contains
  • Python Django filter date
  • Python Django filter order by
  • Python Django filter like
  • Python Django filter greater than
  • Python Django filter less than
  • Python Django filter greater than equal to
  • Python Django filter less than equal to
  • Python Django filter q
  • Python Django filter distinct

Python Django filter

Before starting this topic, one should know what are models in Django and How we can create objects for our model. For this, you can refer to “How to Create a model in Django“.

So, after creating a model and inserting some data. It’s time to learn how we can retrieve the data from the database.

In Django, table data is represented by python objects, and to retrieve these python objects, we have to use QuerySet. A QuerySet in Django is a collection of database objects, and it can have zero or multiple filters. Now, these filters are used to limit down the number of results based upon the parameters provided.

Many times we may come across a situation where we need to select only a subset of objects from all the objects. Now, for this implementation, we will use the QuerySet with some filter conditions. And some command filter methods are given below.

  1. filter(): This methods returns a new QuerySet with objcts that matches the given parameter. And it will also return a QuerySet even when there is only one object that matches the condition. In such cases, the QuerySet will contain only one element.
  2. exclude(): In Django, the exclude() methods returns a new QuerySet with objects that does not matches the given parameter.

So, in the coming sections, we will discuss different examples related to the usability of the filter method with QuerySet.

Read: How to install Django

Python Django filter and

Now, in this section, we will discuss how to use the AND operator while using the filter method in Django. For the demonstration of this topic, we are using the User model in Django. And the model contains the following data.

usernamefirst_namelast_nameemail
MargitMargitWorling[email protected]
MistyMistyBirkby[email protected]
MycahMycahSeville[email protected]
RossRossHanks[email protected]
ScottiScottiMulleary[email protected]
User Model Data

Now, for the execution of this task, we will use the Django shell. And to use the shell, first, we need to open the command prompt and run the following command.

python manage.py shell

This will start the interactive console in the command prompt. Now, we will execute the following example.

(InteractiveConsole)
>>> from django.contrib.auth.models import User                       
>>>
>>> queryset = User.objects.filter(first_name__startswith='M', last_name__startswith='S')
>>>
>>> print(queryset)

In the above example, first, we have imported the User model. After this, we are using QuerySet to filter the data and for the filtering, we have defined 2 conditions.

First, the first_name of a record should start with the character “M“. Second, the last_name of the record should start with the character “S“.

Now, the comma (“,“) between the conditions specifies the AND operator. In the end, we are using the print statement to print the filtered QuerySet.

So, this QuerySet will select the records whose first name starts with “M” and the last name starts with “S“.

Python Django filter and
Result

We can also fetch its corresponding SQL code by executing the following command.

str(queryset.query)

And it will return the equivalent SQL statement for this QuerySet.

Python Django filter and SQL
Output

Read: How to setup Django project

Python Django filter not equal

In this section, we will understand how to filter objects in Django based upon the “Not Equal” condition.

This simply means that we have to filter all the data that does not match the given condition. For this execution, we will use the exclude() method with the QuerySet.

The exclude() method in Django returns a new QuerySet with the objects that do not match the given parameter. Let’s understand its usage by executing an example.

Again, we will use the same User model and also use the Django shell for execution. And here is the example of the exclude() method.

>>> from django.contrib.auth.models import User
>>> 
>>> queryset = User.objects.exclude(first_name__startswith='M')                                                
>>> 
>>> print(queryset)

In the example, we have used the import statement to import the User model. After this, we have defined a QuerySet which will exclude all the records whose first name starts with “M“. And in the end, we use the print statement to print the result.

Python Django filter not equal
Example with Output

Read: Python Django vs Flask

Python Django filter order by

In this section, we will understand how to order the database objects in Django using QuerySet. So, by default, the results by the QuerySet are ordered based upon the ordering tuple defined in the Model’s Meta class.

But, we can also change the ordering of the results by the QuerySet by using the order_by() method.

For the demonstration of this task, we are using the Students model with the following data.

first_namelast_nameAge
BorisGallatly16
TawnyaDulton16
JustinaPavett16
GerrileeTaffurelli17
EdenHawkey17
JerryCaves18
GerardoTichelaar18
YuriMattimoe15
AnissaAlexsandrov15
JanessaChing16
Students Model Data

Now, for the execution, we will use the Django shell and try to order the results based upon the first name in ascending order. And here is the code for the implementation.

>>> from myApp.models import Students
>>> 
>>> queryset = Students.objects.order_by('first_name')
>>> 
>>> print(queryset)

So, in the given example, first, we have imported the Students model. After this, we have defined a QuerySet with the order_by() method. In the order_by() method, we have defined ‘first_name‘ as an argument.

This simply means the objects in the QuerySet will be ordered based upon the first_name in ascending order. To define the order as descending, we have to use the minus sign (-) with the argument.

Here is the execution of the above example with its result.

Python Django filter order by
Example with Output

Read: Python Django get admin password

Python Django filter greater than

In this section, we will discuss how we can use the “greater than” filter with the QuerySet to filter the objects in Django. For this demonstration, again we will use the Students model and its data. The data in the model is as follows.

first_namelast_nameAge
BorisGallatly16
TawnyaDulton16
JustinaPavett16
GerrileeTaffurelli17
EdenHawkey17
JerryCaves18
GerardoTichelaar18
YuriMattimoe15
AnissaAlexsandrov15
JanessaChing16
Students Model Data

Let’s understand how to use the “greater than” operator with the help of an example. And for the example, we are going to select all the database objects whose age is greater than 16. The code for the example is as follows.

>>> from myApp.models import Students
>>> 
>>> queryset = Students.objects.filter(age__gt=16)    
>>> 
>>> print(queryset)

So, in the example, we are using the filter() method and in the method, we have passed “age__gt=16” as an argument. This means it will select all the objects from the Students model whose age is greater than 16. Now, if we run the given code, we will get the following output.

Python Django filter greater than
Example

Read: Difference between app and project in Django

Python Django filter greater than equal to

So, similar to the “greater than” filter, we can also use the “greater than or equal to” (>=) filter in Django. By using this filter, we can select all the database objects which greater than or equal to a particular value.

Again for this demonstration, we are going to use the Students model with the same data as shown in the previous section.

And for the example, we are going to select all the database objects whose age is greater than or equal to 17. The code for this example is given below.

(InteractiveConsole)
>>> 
>>> from myApp.models import Students
>>> 
>>> queryset = Students.objects.filter(age__gte=17)
>>> 
>>> print(queryset) 

So, in the example, we are using the filter() method and in the method, we have passed “age__gte=17” as an argument.

This means it will select all the objects from the Students model whose age is greater than or equal to 17. Now, if we run the given code, we will get the following output.

Python Django filter greater than equal to
Example

Read: How to Get Current time in Django

Python Django filter less than

In this section, we will discuss how we can use the “less than” filter with the QuerySet to filter the objects in Django.

For better understanding, we will understand the implementation with the help of an example. And for this, we will use the same Students model in Django.

For the example demonstration, we are going to select all the database objects whose age is less than 17. The code for the example is given below.

(InteractiveConsole)
>>>                                  
>>> from myApp.models import Students
>>> 
>>> queryset = Students.objects.filter(age__lt=17)  
>>> 
>>> print(queryset)

In the above example, we are using the filter() method with the QuerySet. And in the method, we have passed “age__lt=17” as an argument.

This means it will select all the objects from the Students model whose age is less than 17. Now, if we implement the given code, we will get the following result.

Python Django filter less than
Example

Read Convert HTML page to PDF using Django in Python

Python Django filter less than equal to

In this section, we will discuss how we can use the “less than or equal to” (<=) filter with the QuerySet to filter the objects in Django.

And, we will understand the implementation with the help of an example. For this, we will use the same Students model in Django.

For the example, we are going to select all the database objects whose age is less than or equal to 16. The code for this example is as follows.

(InteractiveConsole)
>>> 
>>> from myApp.models import Students
>>> 
>>> queryset = Students.objects.filter(age__lte=16) 
>>> 
>>> print(queryset)

In the above example, we are using the filter() method with “age__lte=16” as an argument. This will select all the objects from the Students model whose age is less than or equal to 16.

Now, if we implement the given code, we will get the following output of 6 objects.

Python Django filter less than equal to
Example

Read Python Django get

Python Django filter contains

In Django, we can also search objects based upon the given pattern and contains filter is used for this task. The contains filter in Django returns all the objects that carry case-sensitive strings in the given field.

Let’s understand its usage with the help of an example and we will use the Person model in the example.

first_namelast_nameAge
ZakDawidowsky23
JonathonGaule19
ZakRandall21
KristiBrinkley20
ZakMacCoughan24
Jonathon McCoveney27
Jonathon Tanswell25
Person Model Data

As you can see in the model data, there are multiple records with the same first name but a different last name.

Now, we will use the contains filter to select all the records whose first name is “Zak“. Here is the code of this example.

(InteractiveConsole)
>>> 
>>> from myApp.models import Person
>>> 
>>> queryset = Person.objects.filter(first_name__contains='Zak')
>>> 
>>> print(queryset)

In the given example, we are using the filter method in the QuerySet. And in the filter method, we have passed “first_name__conatains=’Zak’” as an argument.

So, this QuerySet will select all the objects that carry the first name as “Zak“. Here is the execution of the example with the result.

Python Django filter contains
Example

Python Django filter like

In SQL, a LIKE operator is used in the WHERE clause to search the given pattern. But in Django, we cannot directly use the LIKE operator instead we use the contains field lookup in the filter method to search the given pattern.

The example related to contains field lookup is given in the previous section. To confirm whether the contains option is equivalent to the LIKE operator, we will run the following given code.

>>> from myApp.models import Person
>>> 
>>> queryset = Person.objects.filter(first_name__contains='Zak')
>>> 
>>> print(queryset) 

>>> 
>>> str(queryset.query)

In the example, we are using the same example as demonstrated in the previous section. This example is about selecting all the objects whose first name is “Zak” by using contains field lookup.

After this, we are using the str(queryset.query) method and it will return the equivalent SQL code for the given QuerySet.

In the end, we will get the following results.

Python Django filter like
Result

Python Django filter in

In SQL, we generally use the IN operator to specify multiple values in the Where clause. Similarly, in Django, we can use the “in” field lookup to select the objects that contain values that are there in the given iterable.

Now, these given iterable can be a list, tuple, queryset, or even strings.

Let’s understand the use of the “in” field lookup with the help of an example. For this, we will use the same Person model.

And, for the example, we are going to use the following code in the interactive console (Django shell).

(InteractiveConsole)
>>> 
>>> from myApp.models import Person
>>>                
>>> queryset = Person.objects.filter(pk__in=[1,4,8]) 
>>> 
>>> print(queryset)

In the example, we are simply using the “in” field lookup to select the objects which have primary-key values like 1, 4, and 8. And it will return all the three objects having these primary key values.

Python Django filter in
Output

Python Django filter date

In the section, we will understand how to filter database objects by a given date range in Django. In this, we will learn how to select the objects that fall under the given date range.

For this demonstration, we are using the following Employee model. And this model has the following data.

NameJob TitleJoining DateSalary
Hardy MuncerSenior Financial Analyst2021-05-2524000
Ric RuffleProduct Engineer2021-02-1340000
Rhoda BenzGeneral Manager2020-10-1735000
Rustin FlippelliFinancial Analyst2021-06-0420000
Denys ButtingTechnical Writer2020-11-2332000
Allene JohanssonDatabase Administrator2021-04-2128000
Amye RoonyAccounting Assistant2020-10-0223000
Willie PhilpsEngineer II2021-08-0132000
Employee Model Data

Now, for the example demonstration, we will select all the employee records where the joining date is between “2020-10-02” and “2021-05-02” (yyyy-mm-dd). Here is the code of the example.

(InteractiveConsole)
>>>                                
>>> from myApp.models import Employee
>>> 
>>> queryset = Employee.objects.filter(joining_date__range=["2020-10-02","2021-05-02"])
>>> 
>>> print(queryset)

In the above example, we are using the range field lookup to select all the database objects where the joining date is between “2020-10-02” and “2021-05-02“.

And to define the range, we have defined the dates in the range list. So, after implementing the above example, we will get the following output.

Python Django filter date
Output

Python Django filter q

In Django, we can use the Q() object to implement complex SQL queries. We can use a Q() object to represent a SQL statement which can be utilized for some database operations.

This operator allows to define and reuse the conditions and it also allows to combine them with operators like “OR” and “AND“.

A Q() object (django.db.models.Q) is a container for a set of keyword parameters. These keyword parameters are given in the same way as the “Field lookups”. So, let’s understand its usage with the help of an example.

Now, for the example demonstration, we are going to use the same Employee model which is shown in the previous section. And we will try to select all the objects from the Employee model whose name starts with “R“.

(InteractiveConsole)
>>> from myApp.models import Employee
>>> from django.db.models import Q
>>> 
>>> queryset = Employee.objects.filter(  
... Q(name__startswith="R")
... )
>>> 
>>> print(queryset)

In the above example, first, we have imported the Employee model and then, we have imported the Q() object from django.db.models. After the, we have created a QuerySet with the filter method and in the method, we have used the Q() object.

So, this QuerySet with return a new QuerySet where the name of the object starts with “R“. Here is the result of the above example.

Python Django filter q
Result

Read: Python Django group by

Python Django filter or

In Django, we cannot directly use the OR operator to filter the QuerySet. For this implementation, we have to use the Q() object. By using the Q() object in the filter method, we will be able to use the OR operator between the Q() objects.

Let’s understand the implementation with the help of an example. For this example, we will use the Employee model. And we will try to select all the objects from the employee model whose name either starts with “A” or “R“.

(InteractiveConsole)
>>>  
>>> from myApp.models import Employee
>>> from django.db.models import Q     
>>> 
>>> queryset = Employee.objects.filter(
... Q(name__startswith="A")|Q(name__startswith="R")
... )
>>> 
>>> print(queryset)

In the example, we are using the filter method in the QuerySet. And in the filter method, we are using 2 Q() objects with field lookups statements. And between these Q() statements, we have defined the OR (|) operator. In the end, we are using a print statement to print the QuerySet.

Python Django filter or
Output

Read: Django for loop

Python Django filter distinct

In SQL, we use the DISTINCT keyword in the SELECT statement to select unique records. We generally use the SELECT DISTINCT statement to remove all the duplicate records from the query result.

In the same way, we use the distinct() method in Django to remove the duplicate records from the QuerySet.

For the demonstration of this method, we are going to use the Customer model with the following set of records.

NameAddressCountryCity
Astra De Fries8268 Texas CircleUnited StatesBuffalo
Bowie McSperron3 Eggendart Trail United States Clearwater
Clarinda Kemme78214 Buell PassCanadaShediac
Shane Frensch35456 Trailsway Hill United States Detroit
Cortney Davidsson94999 Little Fleur DriveUnited KingdomKinloch
Queenie Gravie8860 Norway Maple PointUnited KingdomAshley
Dulcy Fishlock85095 Debs CrossingUnited StatesMiami Beach
Teodorico Puzey04977 Chive CircleCanadaBowen Island
Customer Model Data

Now, for the example, we will select the distinct country names and we will use the following code.

Note:- The distinct() method with an argument is not supported by the default SQLite database. So, in the example, we have shown one way to use the distinct method in the SQLite database.

(InteractiveConsole)
>>> from myApp.models import Customer   
>>> 
>>> queryset = Customer.objects.values('country').distinct()
>>> 
>>> print(queryset)

The above QuerySet will return all the distinct values from the country column. Here is the execution of the above example.

Python Django filter distinct
Example

Also, read: Get URL parameters in Django

In this Django Tutorial, we have discussed “Python Django filter” and we have also discussed the following topics in this tutorial.

  • Python Django filter
  • Python Django filter or
  • Python Django filter and
  • Python Django filter in
  • Python Django filter not equal
  • Python Django filter contains
  • Python Django filter date
  • Python Django filter order by
  • Python Django filter like
  • Python Django filter greater than
  • Python Django filter less than
  • Python Django filter greater than equal to
  • Python Django filter less than equal to
  • Python Django filter q
  • Python Django filter distinct