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?
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)]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With