How to Use __contains Lookup in Django Queries
In Django, use the
__contains lookup in queryset filters to find records where a field contains a specific substring. For example, Model.objects.filter(field__contains='text') returns all objects with 'text' inside the specified field.Syntax
The __contains lookup is used in Django ORM queries to filter records where a field contains a given substring. It is appended to the field name with double underscores.
Model.objects.filter(field__contains='value'): Finds records wherefieldincludes'value'.- The lookup is case-sensitive.
python
Model.objects.filter(field__contains='substring')
Example
This example shows how to filter a list of books whose titles contain the word 'Django'. It demonstrates the use of __contains in a Django queryset.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) # Assume some Book objects exist # Query to find books with 'Django' in the title books_with_django = Book.objects.filter(title__contains='Django') for book in books_with_django: print(book.title)
Output
Django for Beginners
Mastering Django
Learning Django
Common Pitfalls
Common mistakes when using __contains include:
- Expecting case-insensitive matching (use
__icontainsinstead). - Using
__containson non-text fields (it only works on text-based fields). - Forgetting that
__containsmatches substrings anywhere in the field, not just prefixes or suffixes.
Example of wrong and right usage:
python
# Wrong: case-insensitive search with __contains (won't work as expected) Book.objects.filter(title__contains='django') # misses 'Django' # Right: use __icontains for case-insensitive search Book.objects.filter(title__icontains='django')
Quick Reference
| Lookup | Description | Case Sensitivity |
|---|---|---|
| field__contains='value' | Matches records where field contains 'value' | Case-sensitive |
| field__icontains='value' | Matches records where field contains 'value' ignoring case | Case-insensitive |
Key Takeaways
Use __contains to filter records where a text field includes a substring with case sensitivity.
For case-insensitive substring matching, use __icontains instead of __contains.
__contains works only on text-based fields like CharField or TextField.
Remember that __contains matches the substring anywhere inside the field value.
Always test queries to ensure they return expected results, especially with case sensitivity.