How to exclude two conditions in query via Django ORM?

Question:

How can I exclude by two conditions which are connected via a logical OR:

Object.objects.filter(country_send=country).exclude(status__exact='').order_by('-id')
Object.objects.filter(country_send=country).exclude(status__exact='deleted').order_by('-id')

I’m trying to exclude the object with no status and status "deleted".

Asked By: user3657840

||

Answers:

You can try using “lists”. On status list you can add all the words you want.

status = ['deleted', '']
Object.objects.filter(country_send=country).exclude(status__in=status).order_by('-id')

More about list: http://www.sthurlow.com/python/lesson06/

Answered By: Marcos Aguayo

Have a look to Q Objects

Your query will be:

from django.db.models import Q
Object.objects.filter(country_send=country).exclude(Q(status__exact='') | Q(status__exact='deleted')).order_by('-id')
Answered By: xecgr

You might consider chaining exclude calls together:

Object.objects.filter(country_send=country).exclude(status='').exclude(status='deleted').order_by('-id')

This has the affect acting like an or operator, and is more readable than using the Q() Object.

The “list” approach from Marcos above is likely best in your case, but my approach would be useful if you are “or-ing” on different fields:

Book.objects.exclude(author='Joe').exclude(publish_year='2018')

This will return all Books and exclude the ones that are either authored by Joe, OR published in 2018.

Answered By: Landon

You can do it by using Q

from django.db.models import Q
Model.objects.filter(country_send=country, ~Q(status__in=['deleted', ''])).order_by('-id')
Answered By: Sam