'In django how can I run a query that the values of (fielda, fieldb) are in an allowed set of pairs (1, 2), (3, 4)?
In django how can I run a query that (fielda, and fieldb) are in an allowed set of pairs (1, 2), (3, 4)? It doesn't look like this is possible using filter or Q queries. Is it? Or do I need to do this with a raw sql query?
This is how one does it with a raw sql query: https://dba.stackexchange.com/questions/34266/selecting-where-two-columns-are-in-a-set
Solution 1:[1]
You can chain together as many Q objects as you like to create a series of conditions OR'd together.
An example where the pairs are already known:
Model.objects.filter(Q(fielda=1) & Q(fieldb=2) | Q(fielda=3) & Q(fieldb=4))
A more dynamic option to generate the query from an iterable is to create a Q object and then update it with additional conditions in a loop:
pairs = [(1, 2), (3, 4)]
query = Q()
for a, b in pairs:
query |= Q(fielda=a) & Q(fieldb=b)
Model.objects.filter(query)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Iain Shelvington |
