0

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

Community
  • 1
  • 1
David Schumann
  • 13,380
  • 9
  • 75
  • 96

1 Answers1

1

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)
David Schumann
  • 13,380
  • 9
  • 75
  • 96
  • 1
    Here is a one liner: `q = reduce(operator.or_, ((Q(language=lang) & Q(country=country)) for lang, country in my_tuples)) ` – karthikr Jun 11 '15 at 17:32