【发布时间】:2013-11-30 07:05:36
【问题描述】:
如果查询在列表中,以下是 Django 过滤:
options = [1,2,3]
result = Example.objects.filter('something__property__in'=options)
所以这里something 是ForeignKey 与Example 的关系(具有多个关系)
我希望result 是所有something 为1 AND 2 AND 3 的Examples。上面的示例代码将是1 OR 2 OR 3。这将是排他性的!
示例
以下内容将不在result:
examples = Example.objects.all()
things = examples[0].something.all()
for thing in things: print thing.property
#1
#2
#4
#7
以下内容位于result:
examples = Example.objects.all()
things = examples[0].something.all()
for thing in things: print thing.property
#1
#2
#8
#9
#3
第二个示例的原因是 options 中的所有内容,其中第一个示例有 1 和 2,但没有 3!
在 Django 中是否有一种简单的方法可以做到这一点?
我唯一能想到的就是使用上面给出的示例进行过滤,将所有properties 放入一个列表中。并将列表与以下python函数中的options进行比较:
def exclusive_in(list1,list2):
count = 0
for i in list1:
if i in list2:
count += 1
if count == len(list2):
return True
else:
return False
我觉得 Django 可以在它对数据库的查询中做到这一点,这样会更有效率。有什么想法吗?
注意:
这必须适用于options 中任意数量的项目,它可以是大于 2 的任何数字,甚至是 10 或 100(虽然不太可能是 100,但仍有可能)
还要注意options 将由字符串填充
【问题讨论】: