Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django exclude query, can i pass multiple parameters?

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

like image 440
Rishabh Bhardwaj Avatar asked Nov 15 '25 13:11

Rishabh Bhardwaj


1 Answers

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.

like image 67
Willem Van Onsem Avatar answered Nov 18 '25 15:11

Willem Van Onsem