Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude two conditions in query via Django ORM

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".

like image 842
user3657840 Avatar asked Sep 01 '14 09:09

user3657840


People also ask

How does exclude work in Django?

The exclude() method from the QuerySet class returns all objects that do not match the given keyword arguments. So whatever data matches the parameter that is passed into the exclude() method will be excluded from the returned QuerySet.

What is Django's ORM?

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.


2 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/

like image 68
Marcos Aguayo Avatar answered Oct 08 '22 23:10

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')
like image 40
xecgr Avatar answered Oct 08 '22 23:10

xecgr