How to Use __gt, __lt, __gte, __lte in Django Queries
In Django, use
__gt, __lt, __gte, and __lte as lookup suffixes in queryset filters to compare field values. They stand for greater than, less than, greater than or equal to, and less than or equal to respectively, allowing you to filter data based on numeric or date comparisons.Syntax
These lookup expressions are used in Django ORM's filter() method to compare field values.
field__gt=value: Selects records wherefieldis greater thanvalue.field__lt=value: Selects records wherefieldis less thanvalue.field__gte=value: Selects records wherefieldis greater than or equal tovalue.field__lte=value: Selects records wherefieldis less than or equal tovalue.
python
Model.objects.filter(field__gt=value) Model.objects.filter(field__lt=value) Model.objects.filter(field__gte=value) Model.objects.filter(field__lte=value)
Example
This example shows how to filter a list of products by price using these lookup expressions.
python
from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=8, decimal_places=2) # Assume we have some products saved # Get products with price greater than 50 expensive_products = Product.objects.filter(price__gt=50) # Get products with price less than or equal to 20 cheap_products = Product.objects.filter(price__lte=20) # Print names of expensive products for product in expensive_products: print(f"Expensive: {product.name} - ${product.price}") # Print names of cheap products for product in cheap_products: print(f"Cheap: {product.name} - ${product.price}")
Output
Expensive: Laptop - $999.99
Expensive: Smartphone - $799.99
Cheap: Pen - $1.50
Cheap: Notebook - $15.00
Common Pitfalls
Common mistakes include:
- Using these lookups on non-comparable fields like text without numeric or date meaning.
- Confusing
__gtwith__gte(greater than vs. greater than or equal to). - Forgetting to use double underscores
__between the field name and lookup. - Not handling empty querysets which return no results if no records match.
python
wrong = Product.objects.filter(price_gt=50) # Missing double underscore right = Product.objects.filter(price__gt=50)
Quick Reference
| Lookup | Meaning | Example Usage |
|---|---|---|
| __gt | Greater than | price__gt=100 |
| __lt | Less than | price__lt=50 |
| __gte | Greater than or equal to | date__gte='2023-01-01' |
| __lte | Less than or equal to | date__lte='2023-12-31' |
Key Takeaways
Use __gt, __lt, __gte, __lte in Django queryset filters to compare field values.
Always include double underscores between the field name and lookup suffix.
These lookups work well with numeric and date fields for range filtering.
Remember __gte and __lte include equality, unlike __gt and __lt.
Check your queryset results to handle cases with no matching records.