0
0
DjangoHow-ToBeginner · 3 min read

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 where field is greater than value.
  • field__lt=value: Selects records where field is less than value.
  • field__gte=value: Selects records where field is greater than or equal to value.
  • field__lte=value: Selects records where field is less than or equal to value.
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 __gt with __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

LookupMeaningExample Usage
__gtGreater thanprice__gt=100
__ltLess thanprice__lt=50
__gteGreater than or equal todate__gte='2023-01-01'
__lteLess than or equal todate__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.