How to Use __in Lookup in Django Querysets
In Django, use the
__in lookup to filter querysets by checking if a field's value is in a list or iterable. For example, Model.objects.filter(field__in=[value1, value2]) returns objects where field matches any value in the list.Syntax
The __in lookup is used with Django queryset filters to check if a field's value is inside a given list or iterable.
Model.objects.filter(field__in=iterable): Returns objects wherefieldmatches any item initerable.field: The model field you want to filter on.iterable: A list, tuple, or any iterable containing values to match.
python
Model.objects.filter(field__in=[value1, value2, value3])Example
This example shows how to filter Book objects whose id is in a list of IDs.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) # Assume we have books with IDs 1, 2, 3, 4, 5 # Filter books with IDs 2, 4, and 5 books = Book.objects.filter(id__in=[2, 4, 5]) for book in books: print(book.title)
Output
The output will list the titles of books with IDs 2, 4, and 5.
Common Pitfalls
Common mistakes when using __in include:
- Passing a non-iterable value (like a single integer) instead of a list or tuple.
- Using an empty list, which returns no results.
- Confusing
__inwith__exactwhich matches a single value.
Example of wrong and right usage:
python
# Wrong: passing a single value instead of a list books_wrong = Book.objects.filter(id__in=5) # This will raise a TypeError # Right: passing a list books_right = Book.objects.filter(id__in=[5])
Quick Reference
| Usage | Description |
|---|---|
| field__in=[val1, val2] | Filters objects where field matches any value in the list |
| field__in=iterable | Accepts any iterable like list, tuple, or queryset |
| field__in=[] | Returns empty queryset (no matches) |
| field__in=single_value | Incorrect: must be iterable, not single value |
Key Takeaways
Use __in lookup to filter queryset fields matching any value in a list or iterable.
Always pass an iterable (list, tuple, queryset) to __in, never a single value.
An empty list with __in returns no results.
Use __in for multiple value matching instead of multiple OR filters.
Check your iterable type to avoid errors with __in lookup.