Django exclude query, can i pass multiple parameters?

2.3k views Asked by At

I have a query and i want to exclude null companies as well as specific user email.

Demo.objects.all().exclude(company__isnull=True, email="[email protected]")

but seems like above exclude does not work with multiple arguments, my return queryset has email="[email protected]" in it.

If i try above query with single arguments, it works. but not working with multiple arguments. Anyone has any idea how to pass multiple arguments in django exclude ?

Thanks

3

There are 3 answers

0
willeM_ Van Onsem On

You can do this, but then you say exclude all Demos that have company__isnull=True, and as email '[email protected]'. This thus means that if only one of the two conditions is met, it is not excluded.

You can work with Q objects, like:

from django.db.models import Q

Demo.objects.exclude(
    Q(company__isnull=True) |
    Q(email='[email protected]')
)

But it is likely more readable with:

Demo.objects.exclude(
    company__isnull=True
).exclude(
    email='[email protected]'
)

this will thus exclude items for which company is NULL and exclude items for which email is '[email protected]'. So here we exclude it from the moment at least one condition is satisfied.

0
Ahmed I. Elsayed On

Your logic is not right, this is excluding every Demo that has no company and has an email of [email protected]. You may want to chain exclude() calls instead.

Demo.objects.all().exclude(company__isnull=True).exclude(email="[email protected]")
0
ksmehta On

Queries are lazy, nothing happens until you try to pull data from it, so there's no downside to using .exclude() more than once.

Demo.objects.exclude(
    company__isnull=True
).exclude(
    email='[email protected]'
)

Another way is to use Q objects that can be combined using the & and | operators.

# Import
from django.db.models import Q

# Exclude query
exclude_query = Q()
exclude_query.add((~Q(company__isnull=True), Q.OR)
exclude_query.add((~Q(email="[email protected]"), Q.OR)

# Get final objects which excludes email "[email protected]" and null companys
result = Demo.objects.filter(exclude_query)