Created
November 22, 2019 10:21
-
-
Save kezabelle/195392b1dd8a1cced512cdd1bc4f3b34 to your computer and use it in GitHub Desktop.
Different ways to OR in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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