Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django Q object nested with reduce

Tags:

django

Got very complex query (please do not try to solve example - the problem is more complex)

crit=[]
crit.append(Q(firstcond = name) | Q(firstcond__isnull = True)
crit.append(Q(secondcond = name) | Q(firstcond__isnull = True)

MyObject.objects.filter(reduce(operator.and_, crit))

This works as expected:

WHERE (firstcond = name OR firstcond IS NULL) AND (secondcond = name OR secondcond IS NULL)

But now I need some OR:

WHERE ((firstcond = name OR firstcond IS NULL) AND (secondcond = name OR \
secondcond IS NULL)) OR (third = value)

I can't add third int crit list, because operator.and_ in reduce. I have to add operator._or after reduce, but HOW?

like image 299
Tomasz Brzezina Avatar asked Oct 20 '25 18:10

Tomasz Brzezina


1 Answers

No need to use reduce:

crit = (Q(firstcond = name) | Q(firstcond__isnull = True)) & (Q(secondcond = name) | Q(firstcond__isnull = True)) | Q(third = value)
MyObject.objects.filter(crit)

If you want reduce for some reason:

MyObject.objects.filter(reduce(operator.and_, crit) | Q(third = value))

Or:

MyObject.objects.filter(reduce(operator.or_([reduce(operator.and_, crit), Q(third = value)]))
like image 163
serg Avatar answered Oct 23 '25 07:10

serg