How to Use __icontains in Django for Case-Insensitive Filtering
In Django, use the
__icontains lookup in queryset filters to find records where a field contains a specified substring, ignoring case. For example, Model.objects.filter(name__icontains='abc') returns all objects with 'abc' anywhere in the name, case-insensitively.Syntax
The __icontains lookup is used in Django queryset filters to perform a case-insensitive search for a substring within a field's value.
It follows this pattern:
Model.objects.filter(field_name__icontains='substring')
Here, field_name is the model field you want to search, and 'substring' is the text you want to find inside that field, ignoring case differences.
python
Model.objects.filter(field_name__icontains='substring')
Example
This example shows how to filter a list of books to find those whose titles contain the word 'django', regardless of uppercase or lowercase letters.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) # Assume we have these books in the database: # Book(title='Learning Django') # Book(title='Django for Beginners') # Book(title='Python Basics') # Query to find books with 'django' in the title, case-insensitive books = Book.objects.filter(title__icontains='django') for book in books: print(book.title)
Output
Learning Django
Django for Beginners
Common Pitfalls
Common mistakes when using __icontains include:
- Using
__containsinstead, which is case-sensitive and may miss matches. - Passing non-string values to
__icontains, which expects a string. - Forgetting that
__icontainsworks only on text-based fields likeCharFieldorTextField.
Example of wrong and right usage:
python
# Wrong: case-sensitive search Model.objects.filter(name__contains='abc') # Right: case-insensitive search Model.objects.filter(name__icontains='abc')
Quick Reference
| Lookup | Description | Case Sensitive |
|---|---|---|
| __contains | Checks if field contains substring | Yes |
| __icontains | Checks if field contains substring ignoring case | No |
Key Takeaways
Use __icontains in Django queryset filters to search text fields ignoring case.
It works only with string-based fields like CharField or TextField.
Avoid using __contains if you want case-insensitive matching.
Pass a string value to __icontains to avoid errors.
It helps find substrings anywhere inside the field value.