Django: OR with multiple statements

Viewed 335

I want to fetch an object, sometimes with one condition and some other time adding (OR) another condition.

With Laravel (PHP), this is easy to do:

$q = MyModel::where('col1', $val1);
if ($userWantsToAddAnotherOrCondition) {
    $q = $q->orWhere('col2', $val2);
}

At the end I have a query either with condition 'col1' = $va1 or 'col1' = $va1 OR 'col2' = $val2.

In Django (python), I only know this way:

q = MyModel.objects.filter(Q(col1=val1) | Q(col2=val2))

How can I add the second condition (col2=val2) with another statement ?

2 Answers

You can just chain Q objects with the logical or operator |. For example:

cond = Q(col1=val1)
if some_condition:
    cond |= Q(col2=val2)

q = MyModel.objects.filter(cond)

You can also use the union() QuerySet method.

q1 = MyModel.objects.filter(cond1)
q2 = MyModel.objects.filter(cond2)
q3 = MyModel.objects.filter(cond3)

q2.union(q1)
q3.union(q1)
Related