How to Use __range in Django for Filtering Querysets
In Django, use the
__range lookup in queryset filters to select records where a field's value falls between two values. It works like a BETWEEN clause in SQL and requires a tuple or list with two elements representing the start and end of the range.Syntax
The __range lookup is used in Django queryset filters to find records where a field's value is within a given range. It requires a tuple or list with exactly two values: the start and the end of the range.
field__range=(start, end): Filters records wherefieldis betweenstartandend, inclusive.
python
Model.objects.filter(field__range=(start_value, end_value))Example
This example shows how to filter a list of products with prices between 10 and 50 using __range. It returns all products priced from 10 up to 50 inclusive.
python
from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=6, decimal_places=2) # Query to get products priced between 10 and 50 products_in_range = Product.objects.filter(price__range=(10, 50)) for product in products_in_range: print(f"{product.name}: ${product.price}")
Output
Product1: $15.00
Product2: $30.00
Product3: $50.00
Common Pitfalls
Common mistakes when using __range include:
- Passing a list or tuple with more or fewer than two elements causes errors.
- Using
__rangeon non-comparable fields like text without numeric or date meaning. - Confusing
__rangewith__in, which checks for exact matches in a list, not a range.
Correct usage example:
python
# Wrong: too many values Model.objects.filter(field__range=(1, 5, 10)) # Error # Right: exactly two values Model.objects.filter(field__range=(1, 5))
Quick Reference
| Lookup | Description | Example |
|---|---|---|
| field__range | Filters values between two bounds inclusive | Model.objects.filter(age__range=(18, 30)) |
| field__in | Filters values matching any in a list | Model.objects.filter(age__in=[18, 20, 25]) |
Key Takeaways
Use __range with exactly two values to filter between start and end inclusively.
__range works like SQL BETWEEN for numeric or date fields.
Do not confuse __range with __in; __in matches exact values, __range matches a range.
Passing wrong number of values to __range causes errors.
Use __range for clear, readable range filtering in Django queries.