如果查询在列表中,则以下是用于过滤的Django:
options = [1,2,3]
result = Example.objects.filter('something__property__in'=options)
所以此处something
与ForeignKey
的{{1}}关系(具有多个关系)
我希望Example
成为result
为1 AND 2 AND 3的所有Examples
。上面的示例代码为1 OR 2 OR 3.这将是独占的!
以下 不在something
:
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
中的所有内容,其中第一个例子有1和2,但不是3!
在Django中有一种简单的方法吗?
我能想到的唯一事情就是过滤上面给出的示例,在列表中获取所有options
。并在以下python函数中将列表与properties
进行比较:
options
我觉得Django可以在对数据库的查询中做到这一点,这会更有效率。有什么想法吗?
这必须适用于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
中的任意数量的项目,它可以是大于2,甚至10或100的任何数字(尽管100不太可能,但仍有可能)
还要注意options
将填充字符串
答案 0 :(得分:3)
我所知道的唯一方法是使用extra
方法传递查询某些自定义条件。
Django won't allow you使用tables
param传递此条件,因此它必须位于where
中。请参阅以下示例django.contrib.auth models
(示例中的管理员组具有所有权限):
>>> from django.contrib.auth import models
>>> permissions_id = [1,2]
>>> where = """(select count(1)
... from auth_group_permissions gp
... where gp.permission_id in ({})
... and gp.group_id = auth_group.id) = {}"""
>>> where = where.format(','.join(map(str, permissions_id)),
... str(len(permissions_id )))
>>> models.Group.objects.extra(where=[where]).all()
[<Group: Admin>]
>>> print models.Group.objects.extra(where=[where]).all().query
SELECT `auth_group`.`id`, `auth_group`.`name`
FROM `auth_group` WHERE (select count(1)
from auth_group_permissions gp
where gp.permission_id in (1,2)
and gp.group_id = auth_group.id) = 2