I have multiple conditional queries based on whether a variable is set or not and the value of 'doc_type'. But I think it looks ugly and I'm repeating code. Is there a clearer way to get this done?
if status is not None:
if doc_type == 4:
invoices = Invoice.objects.filter(Q(type=4) | Q(type=5) | Q(status=status))
else:
invoices = Invoice.objects.filter(type=doc_type, status=status)
else:
if doc_type == 4:
invoices = Invoice.objects.filter(Q(type=4) | Q(type=5))
else:
invoices = Invoice.objects.filter(type=doc_type)
Are you sure this is what you want?
invoices = Invoice.objects.filter(Q(type=4) | Q(type=5) | Q(status=status))
This will return all invoices where type=4
OR type=5
OR status=Status
.
I think you mean (type is 4 or 5) AND status=status? If so, you can do your Query as follows:
types = [doc_type]
if doc_type == 4:
types.append(5)
invoices = Invoice.objects.filter(type__in=types)
if status is not None:
invoices = invoices.filter(status=status)
You can use Q()
objects if you prefer, but I think that chaining filters is easier to understand in this case.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments