[Django]-How to exclude two conditions in query via Django ORM?

29👍

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/

30👍

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')
👤xecgr

14👍

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.

👤Landon

3👍

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')
👤Sam

Leave a comment