0

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

本质上,我想获取一个列表对象并生成与之等效的对象:

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 就会变得明显。

4

2 回答 2

3
import operator
qobjects = [ ~Q(...), Q(...), Q(...) ]
f = reduce(operator.or_, qobjects)
Examples.objects.filter(*f)
于 2012-12-05T15:21:32.143 回答
1

检查文档以生成 OR 子句

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

import operator
blocks = Examples.objects.filter(reduce(operator.or_, conditions))
# which works as
blocks = Examples.objects.filter(conditions[0]|conditions[1]|...)
于 2012-12-05T15:21:58.493 回答