如何使用迭代器在django中构建查询?

时间:2012-12-05 14:48:06

标签: django django-queryset

如何使用迭代器在django中构建复杂查询?实际上,我觉得这可能比django更像是“基本的蟒蛇”,但它让我感到难过。

基本上,我想获取一个列表对象并生成相当于:

SELECT FROM examples WHERE mystuff LIKE 'EX1' OR mystuff LIKE 'EX2';

以下是我尝试的一些示例代码。

from example.models import Examples
from django.db.models import Q

includes = ['EX1', 'EX2']

conditions = []
# I can do something like this, which does build a list of objects
for ex in excludes:
    conditions.append(~Q(fullblock_icontains='%s' % ex))

# print conditions
# [<django.db.models.query_utils.Q object at 0x03557AB0>, 
# <django.db.models.query_utils.Q object at 0x03557AD0>]

# then I need to do something like this, but obviously this won't work.
blocks = Examples.objects.filter('|'.split(conditions)) 

另外,我会想做同样的事情,但是负面(~Q)。我想,一旦我们计算出LIKE,NOT LIKE就会变得明显。

2 个答案:

答案 0 :(得分:3)

import operator
qobjects = [ ~Q(...), Q(...), Q(...) ]
f = reduce(operator.or_, qobjects)
Examples.objects.filter(*f)

答案 1 :(得分:1)

检查the doc for generating OR clause

要将Q链接在一起,请尝试operator.or_

import operator
blocks = Examples.objects.filter(reduce(operator.or_, conditions))
# which works as
blocks = Examples.objects.filter(conditions[0]|conditions[1]|...)