Construct Django Query with dynamic complex AND + OR structure

126 views Asked by At

I need to query MyField for a list of language:country tuples. (

The SQL I want would be:

SELECT * FROM MyField WHERE
language=my_tuples[0][0] AND country=my_tuples[0][1] OR
language=my_tuples[1][0] AND country=my_tuples[1][1] OR
language=my_tuples[2][0] AND country=my_tuples[2][1] OR
...

I saw this similar question but couldn't quite get it to work: Django: OR queries with dynamic field names

1

There are 1 answers

1
David Schumann On

I figured it out with a bit of tinkering:

    qs = self.MyField.all()
    q = Q()

    for combination in my_tuples:
        q = q | Q(Q(language=combination['language']) & Q(country=combination['country']))

    return qs.filter(q)