Django QuerySet – Filter

Welcome to The Coding College, your go-to resource for learning Django and programming! In this tutorial, we’ll explore Django’s filter() method, a key feature of QuerySets that allows you to fetch specific records from your database.

What is the filter() Method?

The filter() method is used to retrieve records from a database that meet specific conditions. It’s a highly versatile tool in Django’s ORM, enabling precise data queries with minimal code.

How to Use filter()

Syntax

Model.objects.filter(condition)  

Example Model

from django.db import models  

class Product(models.Model):  
    name = models.CharField(max_length=100)  
    price = models.DecimalField(max_digits=10, decimal_places=2)  
    stock = models.IntegerField()  
    is_active = models.BooleanField(default=True)  

Example Query

from .models import Product  

# Get all products priced above $100  
expensive_products = Product.objects.filter(price__gt=100)  

for product in expensive_products:  
    print(product.name, product.price)  

Common Lookups with filter()

Django supports various field lookups for flexible filtering. Here are the most commonly used ones:

LookupDescriptionExample
exactMatches an exact valueprice__exact=100
iexactCase-insensitive exact matchname__iexact='laptop'
containsChecks if a field contains a valuename__contains='phone'
icontainsCase-insensitive containsname__icontains='tablet'
inMatches any value in a listid__in=[1, 2, 3]
gt, ltGreater than, less thanprice__gt=500
gte, lteGreater than or equal, less than or equalprice__lte=200
startswithChecks if a field starts with a valuename__startswith='Mac'
istartswithCase-insensitive starts withname__istartswith='mac'
endswithChecks if a field ends with a valuename__endswith='Pro'
iendswithCase-insensitive ends withname__iendswith='pro'
isnullChecks for NULL valuesstock__isnull=True

Combining Filters

You can combine multiple conditions using logical operators:

AND Conditions

Chaining multiple filter() calls results in an AND operation.

# Products priced above $100 AND in stock  
products = Product.objects.filter(price__gt=100).filter(stock__gt=0)  

Or use a single call:

products = Product.objects.filter(price__gt=100, stock__gt=0)  

OR Conditions

Use the Q object for OR conditions.

from django.db.models import Q  

# Products priced above $100 OR out of stock  
products = Product.objects.filter(Q(price__gt=100) | Q(stock__lte=0))  

Excluding Data

Use the exclude() method to fetch data that does not meet a condition.

# Products not priced above $100  
affordable_products = Product.objects.exclude(price__gt=100)  

Sorting Filtered Data

You can sort filtered data using order_by().

# Products priced above $100, sorted by price (ascending)  
products = Product.objects.filter(price__gt=100).order_by('price')  

# Products sorted by price (descending)  
products = Product.objects.filter(price__gt=100).order_by('-price')  

Pagination of Filtered Data

For large datasets, use Django’s Paginator to handle filtered data.

from django.core.paginator import Paginator  

# Fetch all products priced above $100  
products = Product.objects.filter(price__gt=100)  

# Paginate results (5 products per page)  
paginator = Paginator(products, 5)  

# Get the first page  
page1 = paginator.page(1)  
for product in page1:  
    print(product.name)  

Example: Combining Everything

Here’s a practical example:

from .models import Product  
from django.db.models import Q  

# Get products priced between $50 and $500, in stock, sorted by name  
products = Product.objects.filter(  
    Q(price__gte=50) & Q(price__lte=500) & Q(stock__gt=0)  
).order_by('name')  

for product in products:  
    print(f"Name: {product.name}, Price: {product.price}, Stock: {product.stock}")  

Best Practices for Filtering

  1. Use Lookups Judiciously: Avoid overly complex queries; break them into smaller parts if necessary.
  2. Leverage Indexing: Ensure fields used in filters are indexed for faster queries.
  3. Use .only() and .defer(): Fetch only the necessary fields to optimize database performance.

Learn More at The Coding College

Visit The Coding College for more Django tutorials, tips, and resources. Stay ahead in your Django development journey with in-depth guides tailored for beginners and experts alike!

Final Thoughts

Django’s filter() method is a powerful tool for retrieving specific data from your database. By mastering its various features and combining it with other QuerySet methods, you can create highly efficient and dynamic queries for your web applications.

Leave a Comment