0
0
Djangoframework~5 mins

Field lookups (exact, contains, gt, lt) in Django

Choose your learning style9 modes available
Introduction

Field lookups help you find specific data in your database by matching conditions easily.

You want to find users with a specific exact name.
You need to search for products containing a certain word in their description.
You want to get all orders with amounts greater than a certain value.
You want to list events that happened before a certain date.
Syntax
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).

Examples
Find users whose name is exactly 'Alice'.
Django
User.objects.filter(name__exact='Alice')
Find products with 'organic' anywhere in their description.
Django
Product.objects.filter(description__contains='organic')
Find orders where the amount is greater than 100.
Django
Order.objects.filter(amount__gt=100)
Find events that happened before January 1, 2024.
Django
Event.objects.filter(date__lt='2024-01-01')
Sample Program

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.

Django
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)
OutputSuccess
Important Notes

Field lookups are case-sensitive by default. Use icontains for case-insensitive contains.

Lookups can be combined with other filters for more complex queries.

Summary

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.