Django conditional queries: How can I avoid this?

Eduardo

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)
Alasdair

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.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to avoid excess queries in django template?

From Dev

How can I avoid recursion during saving of django model

From Dev

How can I index these queries?

From Dev

How can I avoid this NullPointerException?

From Dev

How To Avoid Queries in loops

From Dev

How would I combine these queries in Django?

From Java

How can I view live MySQL queries?

From Dev

How can i speed up these linq queries?

From Dev

How can I use @ in PetaPoco queries

From Dev

How can I minimize the amount of queries fired?

From Dev

How can I optimise Zumero sync queries

From Dev

How can I subtract two queries in sql?

From Dev

How can i achieve this in LINQ-Queries?

From Dev

How can I store linq queries?

From Dev

How can I combine these two queries into one?

From Dev

How can I separate SQL queries

From Dev

How can I transform this information to queries?

From Dev

How can I optimise Zumero sync queries

From Dev

How can I improve this queries speed?

From Dev

How can i order by for multiple queries combination

From Dev

How can I add timezone to Esper queries?

From Dev

How can I join 3 SQL queries

From Dev

How can I combine these 2 queries to one?

From Dev

How can I maintain multiple open queries?

From Dev

How can I get these queries to work together?

From Dev

How can I combine these two queries?

From Dev

How can I avoid form.is_valid() flagging an empty field as an error in Django?

From Dev

How can I avoid "database is locked" sqlite3 errors in django?

From Dev

How can I write a conditional without any conditional statements or operators?