This comprehensive guide covers all essential Django ORM lookup types with real-world use cases. Learn how to filter database queries efficiently using:
Basic Lookups
-
exact - Exact match
Product.objects.filter(name__exact='iPhone')
Use case: Find exact product name -
iexact - Case-insensitive exact
User.objects.filter(email__iexact='USER@EXAMPLE.COM')
Use case: Case-insensitive email matching -
contains - Case-sensitive contains
Blog.objects.filter(title__contains='Django')
Use case: Search for titles containing a word -
icontains - Case-insensitive contains
Article.objects.filter(body__icontains='python')
Use case: Full-text search ignoring case
Comparison Lookups
-
gt - Greater than
Product.objects.filter(price__gt=100)
Use case: Find premium products -
gte - Greater than or equal
Order.objects.filter(total__gte=50)
Use case: Minimum order value filter -
lt - Less than
Student.objects.filter(age__lt=21)
Use case: Find underage students -
lte - Less than or equal
Employee.objects.filter(salary__lte=50000)
Use case: Maximum salary threshold -
range - Between values
Product.objects.filter(stock__range=(10, 100))
Use case: Inventory level monitoring
Date/Time Lookups
-
date - Exact date
Log.objects.filter(timestamp__date=date(2023, 1, 1))
Use case: Daily report generation -
year/month/day
Event.objects.filter(start_date__year=2023)
Event.objects.filter(start_date__month=12)
Use case: Yearly/Monthly analytics -
week/week_day
Task.objects.filter(due_date__week=25)
Use case: Weekly task scheduling
Advanced Lookups
-
isnull - Null check
Profile.objects.filter(bio__isnull=True)
Use case: Find incomplete profiles -
in - List containment
Product.objects.filter(category__in=['Electronics', 'Fashion'])
Use case: Multi-category filtering -
regex - Regular expression
User.objects.filter(username__regex=r'^[a-z]{5,}$')
Use case: Validate username patterns -
iregex - Case-insensitive regex
Article.objects.filter(title__iregex=r'\bpython\b')
Use case: Find variations of a word
Relationship Lookups
-
ForeignKey exact
Order.objects.filter(customer__id=5)
Use case: All orders by customer ID -
ManyToMany
Blog.objects.filter(tags__name='Django')
Use case: Posts tagged with specific keyword
Aggregation Lookups
-
count
Store.objects.annotate(product_count=Count('products'))
Use case: Count products per store -
sum/avg
Order.objects.aggregate(total=Sum('amount'))
Use case: Calculate total sales
Special Field Lookups
-
JSONField contains
Product.objects.filter(metadata__contains={'color': 'red'})
Use case: Filter by JSON attributes -
ArrayField contains
Post.objects.filter(tags__contains=['important'])
Use case: Find posts with specific tags