Search code examples
djangodjango-modelsdjango-viewsdjango-q

Q queries in Django


If I have the following query

return Table.objects.filter(Q(cond1) | Q(cond2))

is there a way to know which condition has given a specific row?


Solution

  • You can split your query in two queries:

    qs1 = Table.objects.filter(cond1).extra(select={'condition': 'cond1'})
    qs2 = Table.objects.filter(cond2).extra(select={'condition': 'cond2'})
    

    Then create a union of the querysets:

    qs12 = qs1 | qs2

    EDITED: Unions are not supported between querysets with extra()

    Then create a chain of your querysets:

    from itertools import chain
    
    qs12 = list(chain(qs1, qs2))
    

    And use it like this:

    for obj in qs12:
        if obj.condition == 'cond1':
            ...
        elif obj.condition == 'cond2':
            ...