Perform OR Condition in Django Queryset
Last Updated :
06 Aug, 2024
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 data with OR conditions. This article is going to walk you through the ways of OR conditions in Django QuerySets with Q objects and how to combine such queries, along with practical examples.
Using Q Objects
These are Django's Q objects, which encapsulate a collection of keyword arguments usable in complex queries. They allow you to perform OR and other complex queries easily.
To use Q objects, you'll need to import them from django.db.models. The Q object allows one to construct complex queries easily by joining several conditions together using the | and & operators. Here is some basic example of using Q objects:
Python
from myapp.models import MyModel
from django.db.models import Q
# Example of an OR condition
queryset = MyModel.objects.filter(Q(field1=value1) | Q(field2=value2))
This example will include all objects in the queryset where field1 equals value1 or field2 equals value2.
Combining Queries
You can sometimes be interested in ORing a bit across multiple queries. This is done by passing querysets to be combined using the | operator. You can do this in the following way:
Python
from myapp.models import MyModel
# First query
queryset1 = MyModel.objects.filter(field1=value1)
# Second query
queryset2 = MyModel.objects.filter(field2=value2)
# Combining queries using OR
combined_queryset = queryset1 | queryset2
The combined_queryset will include all objects from queryset1 and queryset2. This method is useful when you need to perform OR operations across different queries or filters.
Examples to Perform OR Condition in Django Queryset
Example 1: Simple OR Condition
Suppose you have a model Book with the fields title and author. You would want to select all books, either having the title "Django for Beginners" or being authored by "John Doe". You can use the following query:
Python
from myapp.models import Book
from django.db.models import Q
# OR condition using Q objects
books = Book.objects.filter(Q(title="Django for Beginners") | Q(author="John Doe"))
Output:
id | title | author |
---|
1 | "Django for Beginners" | "Jane Smith" |
---|
2 | "Advanced Django" | "John Doe" |
---|
3 | "Python 101" | "John Doe" |
---|
4 | "Django for Beginners" | "John Doe" |
---|
Example 2: Combining Multiple OR Conditions
Suppose you have a model Product with fields in the category, price, and availability. You would want to return only those products that are either in the "Electronics" category or whose price is less than $100. Here is how:
Python
from myapp.models import Product
from django.db.models import Q
# Combining multiple OR conditions
products = Product.objects.filter(Q(category="Electronics") | Q(price__lt=100))
Output:
id | name | category | price |
---|
1 | "Smartphone" | "Electronics" | 299 |
---|
2 | "Laptop" | "Electronics" | 999 |
---|
3 | "Headphones" | "Electronics" | 49 |
---|
4 | "Coffee Maker" | "Appliances" | 79 |
---|
5 | "Book" | "Books" | 15 |
---|
6 | "T-shirt" | "Clothing" | 20 |
---|
7 | "Smartwatch" | "Electronics" | 199 |
---|
Example 3: Combining Queries with OR Condition
If you want to combine results from two different queries, such as getting products in either the "Furniture" category or with availability set to "In Stock", you can do:
Python
from myapp.models import Product
# First query for category
category_query = Product.objects.filter(category="Furniture")
# Second query for availability
availability_query = Product.objects.filter(availability="In Stock")
# Combining the two queries
combined_products = category_query | availability_query
Output:
id | name | category | availability |
---|
1 | "Sofa" | "Furniture" | "In Stock" |
---|
2 | "Chair" | "Furniture" | "Out of Stock" |
---|
3 | "Table" | "Furniture" | "In Stock" |
---|
4 | "Lamp" | "Lighting" | "In Stock" |
---|
5 | "Desk" | "Furniture" | "In Stock" |
---|
6 | "Notebook" | "Stationery" | "In Stock" |
---|
Conclusion
It is easy to perform OR conditions in Django QuerySets using Q objects or by combining queries. Knowing these techniques will help you derive more flexible and powerful queries within your Django applications. Whether you want to filter data according to multiple conditions or combine results from several queries, these methods will enable you to do things efficiently.
Similar Reads
How to perform OR, AND and NOT in Django QuerySet Filtering 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
4 min read
Count() vs len() on a Django QuerySet In Django, when working with database query sets, developers often need to determine the number of records that meet certain criteria. Django offers two primary ways to accomplish this: using the count() method on a QuerySet, or the Python built-in len() function. Each method has its specific use ca
3 min read
Django Query Set - Order By order_by() method in Django QuerySets is used to sort query results based on one or more fields, either in ascending or descending order. This helps display data sorted by criteria like salary, name, date, etc., directly from the database query.In this article we will learn all about order_by method
2 min read
Django Conditional Expressions in Queries The conditional expressions allow developers to make decisions and manipulate data within queries, templates, and Python code, making it easier to create complex and dynamic web applications. In this article, we'll delve into the world of conditional expressions in Django and explore how they can be
4 min read
Checking for Empty QuerySet in Django In Django, the QuerySet is one of the most powerful features of the framework, allowing us to interact with the database by fetching, filtering, and modifying data. However, there are times when we need to determine whether the result of a QuerySet is empty. This is essential for handling scenarios
3 min read