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 or the __ne
field lookup. This article will guide you through how to perform a "not equal" operation in Django queries.
Sample Django Model
[
{"id": 1, "name": "Laptop", "category": "Electronics", "in_stock": True, "order__status": "Delivered"},
{"id": 2, "name": "Shirt", "category": "Clothing", "in_stock": False, "order__status": "Processing"},
{"id": 3, "name": "Book", "category": "Stationery", "in_stock": True, "order__status": "Cancelled"},
{"id": 4, "name": "Mug", "category": "Kitchen", "in_stock": True, "order__status": "Delivered"},
{"id": 5, "name": "Phone", "category": "Electronics", "in_stock": False, "order__status": "Processing"},
{"id": 6, "name": "Pencil", "category": "Stationery", "in_stock": True, "order__status": "Delivered"}
]
Using the exclude()
Method
Django's exclude()
method allows you to filter out records that meet a specific condition. It is essentially the opposite of the filter()
method, which returns objects that match the given criteria. To retrieve records where a field is not equal to a specific value, you can exclude the value you want to avoid.
Example 1: Exclude a Specific Value
Suppose you have a model Product
and you want to exclude products from the category "Electronics."
Python
from myapp.models import Product
# Query for products where the category is NOT 'Electronics'
products = Product.objects.exclude(category='Electronics')
In this example, the exclude()
method returns all products where the category
is not equal to "Electronics." Any product with "Electronics" as its category will be omitted from the result set.
Output
[
{"id": 2, "name": "Shirt", "category": "Clothing", "in_stock": False, "order__status": "Processing"},
{"id": 3, "name": "Book", "category": "Stationery", "in_stock": True, "order__status": "Cancelled"},
{"id": 4, "name": "Mug", "category": "Kitchen", "in_stock": True, "order__status": "Delivered"},
{"id": 6, "name": "Pencil", "category": "Stationery", "in_stock": True, "order__status": "Delivered"}
]
Example 2: Exclude Multiple Values
If you need to filter out multiple values, you can chain multiple exclude()
methods or use Q
objects.
Python
from myapp.models import Product
from django.db.models import Q
# Exclude products where category is 'Electronics' or 'Clothing'
products = Product.objects.exclude(Q(category='Electronics') | Q(category='Clothing'))
Here, products belonging to either "Electronics" or "Clothing" are excluded from the result.
Output
[
{"id": 3, "name": "Book", "category": "Stationery", "in_stock": True, "order__status": "Cancelled"},
{"id": 4, "name": "Mug", "category": "Kitchen", "in_stock": True, "order__status": "Delivered"},
{"id": 6, "name": "Pencil", "category": "Stationery", "in_stock": True, "order__status": "Delivered"}
]
Combining exclude()
with Other Filters
Unlike SQL, Django does not natively support a __ne
(not equal) field lookup. The exclude()
method is the recommended way to handle "not equal" conditions. However, if you need to negate other types of conditions (e.g., "not in" or "not like"), the exclude()
method can still be used.
You can combine exclude()
with filter()
to build complex queries where you need to filter on multiple conditions and also exclude certain records.
Example: Filtering and Excluding Together
Imagine you want to get products that are in stock but not in the category "Electronics."
Python
from myapp.models import Product
# Filter products that are in stock, but not in the 'Electronics' category
products = Product.objects.filter(in_stock=True).exclude(category='Electronics')
In this case, the filter()
method ensures only products that are in stock are returned, while the exclude()
method filters out products in the "Electronics" category.
Output
[
{"id": 3, "name": "Book", "category": "Stationery", "in_stock": True, "order__status": "Cancelled"},
{"id": 4, "name": "Mug", "category": "Kitchen", "in_stock": True, "order__status": "Delivered"},
{"id": 6, "name": "Pencil", "category": "Stationery", "in_stock": True, "order__status": "Delivered"}
]
Using exclude()
with Related Models
You can also use the exclude()
method to filter out records based on related fields. Consider an example where you have a Customer
model related to an Order
model via a foreign key, and you want to exclude customers who have placed orders with a specific status.
Python
from myapp.models import Customer
# Exclude customers who have orders with the status 'Cancelled'
customers = Customer.objects.exclude(order__status='Cancelled')
Here, customers with at least one "Cancelled" order are excluded from the results.
Output
[
{"id": 1, "name": "Laptop", "category": "Electronics", "in_stock": True, "order__status": "Delivered"},
{"id": 2, "name": "Shirt", "category": "Clothing", "in_stock": False, "order__status": "Processing"},
{"id": 3, "name": "Book", "category": "Stationery", "in_stock": True, "order__status": "Cancelled"},
{"id": 4, "name": "Mug", "category": "Kitchen", "in_stock": True, "order__status": "Delivered"},
{"id": 5, "name": "Phone", "category": "Electronics", "in_stock": False, "order__status": "Processing"},
{"id": 6, "name": "Pencil", "category": "Stationery", "in_stock": True, "order__status": "Delivered"}
]
Conclusion
In Django, filtering records where a field is not equal to a certain value is easily done using the exclude()
method. While Django does not have a direct __ne
lookup, the exclude()
method allows you to negate any condition with simplicity and efficiency. Whether you're dealing with simple filters or more complex queries involving related models, exclude()
provides a powerful tool for customizing your database queries.
Similar Reads
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 Query as GROUP BY in Django? In Django, the powerful ORM (Object-Relational Mapping) allows developers to interact with databases using Python code. One common database operation is the GROUP BY query, which groups rows sharing a property so that aggregate functions can be applied to each group. This article will guide you thro
3 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 Do SELECT MAX in Django? When working with databases in Django, we often need to find the highest value of a specific field in a model. Let's say, find the book with the highest price, the product with the highest discount, etc. This is like doing a SELECT MAX query in SQL. In this article, we'll learn how to find the max v
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