Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Created November 22, 2019 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kezabelle/195392b1dd8a1cced512cdd1bc4f3b34 to your computer and use it in GitHub Desktop.
Save kezabelle/195392b1dd8a1cced512cdd1bc4f3b34 to your computer and use it in GitHub Desktop.
Different ways to OR in Django
from django.db.models import Q
from functools import reduce
from operator import or_
values = (
('myfield__iexact', 1),
('myotherfield__iexact', 2),
('myfield__iexact', 3),
('mythirdfield__icontains', 'test'),
)
# Simplest:
q1 = Q()
for v in values:
q1 |= Q(v)
# Classic reduction
q2 = reduce(or_, (Q(x) for x in values))
# Best AFAIK:
q3 = Q(*values)
q3.connector = Q.OR
# Basically the same:
q4 = Q(*(x for x in values), _connector=Q.OR)
assert q1 == q2 == q3 == q4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment