Field lookups help you find specific data in your database by matching conditions easily.
Field lookups (exact, contains, gt, lt) in Django
Model.objects.filter(field__lookup=value)Use double underscores __ to separate the field name and the lookup type.
Common lookups include exact, contains, gt (greater than), and lt (less than).
User.objects.filter(name__exact='Alice')
Product.objects.filter(description__contains='organic')
Order.objects.filter(amount__gt=100)
Event.objects.filter(date__lt='2024-01-01')
This example defines a Product model and shows how to use field lookups to filter products by exact name, description containing a word, price greater than, and price less than.
Printing the query shows the SQL Django will run.
from django.db import models class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) # Example queries products_exact = Product.objects.filter(name__exact='Apple') products_contains = Product.objects.filter(description__contains='fresh') products_gt = Product.objects.filter(price__gt=10.00) products_lt = Product.objects.filter(price__lt=5.00) # For demonstration, print the querysets' query strings print(products_exact.query) print(products_contains.query) print(products_gt.query) print(products_lt.query)
Field lookups are case-sensitive by default. Use icontains for case-insensitive contains.
Lookups can be combined with other filters for more complex queries.
Field lookups let you filter database records by conditions on fields.
Use exact for exact matches, contains for substring matches, gt and lt for greater or less than comparisons.
They make querying your data simple and readable.