How to perform OR, AND and NOT in Django QuerySet Filtering
Last Updated :
20 Aug, 2024
We can use the Q objects in django.db.models to create an OR, AND, and NOT filter in a Django query. The Q objects are used to form complex filtering by joining several conditions through logic operators like OR, AND, and NOT. In this article, we will learn to perform AND, OR, and NOT filters while fetching data from databases using Django ORM.
Introduction to Q Objects
By default, query filters in Django use AND logic. If you need to apply OR logic or if you want to do more complex queries involving multiple logical operations like AND, OR, and NOT, Q objects do the trick. Basically, Q objects can be combined with &, |, and ~ operators.
OR Condition
Imagine you have a model Book with fields title, author, and published_date, and you need to select all book where the title contains "Django" or the author contains "GFG".
Python
from django.db.models import Q
from myapp.models import Book
# Get all books where the title contains "Django" OR
# the author name contains "GFG".
books = Book.objects.filter(Q(title__icontains="Django") | Q(author__icontains="GFG"))
print('Books: ' books)
for book in books:
print(book.title, book.author, sep=', ')
Output:
Book: <QuerySet [<Book: Django for Beginners>, <Book: Coding for All>]>
Django for Beginners, GeeksForGeeks
Coding for All, GFG Learning
AND Condition
If you need to use AND logic to combine conditions explicitly, you can do the following using Q objects as well:
Python
# Get all articles where title contains "Django" AND content contains "Python"
book = Book.objects.filter(Q(title__icontains="Django") & Q(content__icontains="GFG"))
print('Books: ', books)
for book in books:
print(book.title, book.author, sep=', ')
Output:
Books: <QuerySet [<Book: Django Tutorial>]>
Django Tutorial, GFG Learning Center
NOT Condition
You can use the ~ operator (NOT) to exclude certain results.
Python
# Get all books where title does NOT contain "Django"
books = Book.objects.filter(~Q(title__icontains="Django"))
print('Book: ', books)
Output:
Book: <QuerySet [<Book: A technical Writer >, <Book: Biography of GFG>, <Book: Debug ToolBar Guid>, <Book: Coding for All>]>
Combining Multiple Conditions
You can combine several Q objects to create very specific queries.
Example: Complex Query
Get all articles whose title contains the word "Django" OR whose content contains the word "Python", AND whose date of publication is later than 1st January, 2022.
Python
books = Book.objects.filter(
(Q(title__icontains="Django") | Q(author__icontains="GFG")) &
Q(published_date__gt="2024-08-20")
)
for book in books:
print(book.title, book.author, book.published_date, sep=', ')
Output:
Coding for All, GFG Learning, 2024-08-22
Examples to Implement Django QuerySet Filtering
The following are a few examples of the application of Q objects within Django for handling advanced querying cases:
Example 1: Filtering Users by Several Criteria
Suppose you have a User model with fields like first_name, last_name, email, and is_active. You want to retrieve all users whose first name is "John" or last name is "Doe".
Python
from django.db.models import Q
from django.contrib.auth.models import User
# Find users where first name is "John" OR last name is "Doe"
Get all users with first_name John or last_name Doe.
users = User.objects.filter(Q(first_name='John') | Q(last_name='Doe'))
Example 2: Complex AND and OR Conditions
Suppose that you have a Product model defined with name, category and price fields. You want to select all products either in the "Electronics" category or with a price below $50, and in stock.
Python
from django.db.models import Q
from myapp.models import Product
# Find products where (category is "Electronics" OR price < 50) AND in_stock is True
products = Product.objects.filter
(Q(category='Electronics') | Q(price__lt=50)) & Q(in_stock=True)
)
Example 3: Excluding Records with NOT
Let's say you want to get all the records from a BlogPost model, excluding those for which the title includes "Django".
Python
from django.db.models import Q
from myapp.models import BlogPost
# Get all blog posts except those whose title contains "Django"
posts = BlogPost.objects.filter(~Q(title__icontains='Django'))
Example 4: Complex Filtering on Date Fields
Suppose you have an Event model with fields name, start_date, and end_date. Find all the events that either start after the date or have no end date specified.
Python
from django.db.models import Q
from myapp.models import Event
# Find events where start_date is after '2024-01-01' OR end_date is null
events = Event.objects.filter(Q(start_date__gt='2024-01-01') | Q(end_date__isnull=True))
Conclusion
In Django, the OR filter in a query is accomplished by Q objects. They not only facilitate OR but generally provide a way to construct more complex queries than the default AND logic in the module. You can filter using Q objects with the | operator to find results that have either of the conditions. This will come in very handy in a situation where you would want to fetch records that would satisfy at least one of several conditions. It will enhance the flexibility and power in data fetching through Django's ORM.
Similar Reads
How to Perform Query Filtering in Django Templates
Sometimes we may want to filter or modify the list of objects within the template itself to tailor the data being displayed. While filtering should generally be done at the view level for clarity and separation of concerns, Django templates provide some basic filtering capabilities through template
5 min read
Perform OR Condition in Django Queryset
While querying a database using Django's ORMâObject-Relational Mappingâone of the most common requirements would probably be filtering data on more than one condition. By default, Django supports filtering data with AND conditions. However, specific techniques have to be used when you need to filter
3 min read
How to do a not equal in Django queryset
In Django, filtering data from the database is typically done through QuerySet methods provided by Djangoâs ORM (Object Relational Mapping). When you need to filter records where a certain field is not equal to a specific value, Django offers an elegant way to handle this using the exclude() method
4 min read
How to Filter Empty or NULL Fields in Django QuerySet?
When working with a Django project, we often need to filter records where certain fields are either empty or NULL. This is a common requirement, especially when dealing with user-generated data where fields might be left blank. In Django, we can filter a QuerySet where a specific field has no value
3 min read
How to Add Data from Queryset into Templates in Django
In this article, we will read about how to add data from Queryset into Templates in Django Python. Data presentation logic is separated in Django MVT(Model View Templates) architecture. Django makes it easy to build web applications with dynamic content. One of the powerful features of Django is fet
3 min read
How to Dynamically Compose an OR Query Filter in Django
Djangoâs Object-Relational Mapping (ORM) provides developers with a powerful and intuitive way to interact with databases using Python code. One of the advanced features of Django's ORM is the ability to create complex query filters, including OR queries. These are essential when you need to retriev
6 min read
Python Django Queryset Filtering
In Django, QuerySet filtering allows you to retrieve only the data you need from the database. QuerySets help you filter, sort and organize your data efficiently, making it easy to interact with your models.This article will explore how to filter datasets using Djangoâs filter(), exclude() and advan
2 min read
How to Output Django QuerySet as JSON
In Django, a common task for web developers is to return data in JSON format, especially when working with APIs. A Django QuerySet, which is a collection of database queries, can be serialized and output as JSON. This article will guide us through how to output a Django QuerySet as JSON using two me
4 min read
How to Filter ForeignKey Choices in a Django ModelForm
A ForeignKey field allows one model to relate to another in Django. When this field is represented in a form (e.g., a Django ModelForm), it typically displays a dropdown list (a select box) populated with all the objects from the related model. However, there are many scenarios where we may need to
6 min read
How to Query Case-insensitive Data in Django ORM
To query case insensitive data, Django provides several lookup methods that we can use like iexact, icontains, istartswith, iendswith, etc. In this article we will be discussing how to filter and query data from the database without caring if its upper or lowercase using Django ORM.Let's say we have
4 min read