How to Use exclude() in Django ORM for Filtering Querysets
Use Django ORM's
exclude() method to filter out records that match specific conditions from a queryset. It returns a new queryset excluding the objects that meet the given criteria, allowing you to easily omit unwanted data.Syntax
The exclude() method is called on a Django queryset and takes keyword arguments that specify the conditions to exclude. It returns a new queryset without the records matching those conditions.
Model.objects.exclude(field=value): excludes records wherefieldequalsvalue.- You can use lookups like
field__lt,field__contains, etc., insideexclude(). - Multiple conditions inside
exclude()are combined with AND logic.
python
Model.objects.exclude(field=value) Model.objects.exclude(field__lookup=value) Model.objects.exclude(field1=value1, field2__lt=value2)
Example
This example shows how to exclude all users who are staff from the queryset of all users.
python
from django.contrib.auth.models import User # Get all users except staff users non_staff_users = User.objects.exclude(is_staff=True) for user in non_staff_users: print(user.username)
Output
alice
bob
charlie
Common Pitfalls
One common mistake is confusing exclude() with filter(). Remember, exclude() removes records matching the condition, while filter() keeps only those records.
Another pitfall is chaining multiple exclude() calls without understanding that each call filters the current queryset further.
python
from django.contrib.auth.models import User # Wrong: Trying to exclude staff and superusers separately but chaining excludes narrows queryset twice users = User.objects.exclude(is_staff=True).exclude(is_superuser=True) # Right: Use one exclude with multiple conditions combined with OR logic using Q objects from django.db.models import Q users = User.objects.exclude(Q(is_staff=True) | Q(is_superuser=True))
Quick Reference
- exclude(field=value): Remove records where field equals value.
- exclude(field__lt=value): Remove records where field is less than value.
- exclude(field__contains='text'): Remove records containing 'text' in field.
- Multiple conditions inside exclude() use AND logic.
- Chaining exclude() calls applies filters sequentially.
Key Takeaways
Use
exclude() to remove records matching conditions from a queryset.Conditions inside
exclude() combine with AND logic.Chaining multiple
exclude() calls filters the queryset step-by-step.Don't confuse
exclude() with filter(); they do opposite things.You can use field lookups like
__lt, __contains inside exclude().