user1532587
user1532587

Reputation: 1023

How to make a queryset combining multiple ANDs and ORs in django

I need to filter something like this:

(status = 0 OR status = 4) OR (parameter = NONE AND status = 1)

how to I translate this into a django queryset?

Possible solutions

Attempt 1:

obj.filter(Q(status=0) | Q(status=4) | (Q(par=None) & Q(status = 1)))

Real query:
it = it.filter( (Q(respond_status=0) | Q(respond_status=4)) | (Q(respond_status=1) & Q(plant__isnull=True) ))
                                                                             ^
SyntaxError: invalid syntax

Attempt 2:

obj_total = []
    for obj in objs:
        if (obj.status == 0 or obj.status == 4) or (obj.status == 0 and obj.param == None):
            obj_total.append(obj)

    objs = Obj.objects.filter(id__in=[x.id for x in obj_total])

This is realy inefficient

Upvotes: 0

Views: 682

Answers (1)

mtt2p
mtt2p

Reputation: 1906

Use the django Q object

two constraints linked by AND (&) and one linked by or (|)

from django.db.models import Q

Model.objects.filter( (Q(status=1) | Q(status=4)) | ( Q(para=param) & Q(status=1) )                             

Upvotes: 2

Related Questions