用动态复杂的AND + OR结构构造Django Query

时间:2015-06-11 16:58:02

标签: python django django-queryset django-database

我需要查询MyField以获取语言列表:country元组。 (

我想要的SQL是:

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
...

我看到了类似的问题,但却无法完成它的工作: Django: OR queries with dynamic field names

1 个答案:

答案 0 :(得分:1)

我通过一些修补来弄清楚:

    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)