Django查询会获得精确的多重查询 [英] Django queryset get exact manytomany lookup
问题描述
我有一个标签模型的实例列表,例如
I have a pk list of instances of Tag model, say
pk_list = [10, 6, 3]
我有另一个模型,包含m2m字段的标签和一个实际,只包含3个标签(以上的pks)。
I have another model with m2m field of tags and an instance that contains exactly 3 tags (of above pks).
class Node(models.Model):
...
tags = models.ManyToManyField(Tag, related_name='nodes')
我想检索包含精确标签集的节点在我的pk_list中指定。当我做
I'd like to retrieve a Node that contains exact set of tags as specified in my pk_list. When I do
Node.objects.filter(tags__in=pk_list)
它返回三个相同实例的列表
it returns a list of three same instances
[<Node: My node title>, <Node: My node title>, <Node: My node title>]
调用.get()不起作用,因为它必须返回单个实例,显然。
Calling .get() doesn't work cause it have to return a single instance, obviously.
那么如何检索单个实例?
我必须注意,如果我的pk_list是不同的例如。 [10,6]或[10,6,3,7]然后我什么也不收。我需要一个精确的匹配。
So, how do I retrieve a single instance? I must note that if my pk_list was different eg. [10, 6] or [10, 6, 3, 7] then I must receive nothing. I need an exact matching.
谢谢
推荐答案
使用过滤器链:
node_query = Node.objects.all()
pk_list = [10, 6, 3]
for pk in pk_list:
node_query = node_query.filter(tags=pk)
现在,node_query将匹配节点,它具有至少三个具有pk 10,6,3的标签。要精确匹配三个标签:
Now node_query will match node, that has at least three tags with pk 10, 6, 3. To exact matching of three tags:
更新:
感谢 @janos 和<一个href =https://stackoverflow.com/users/1959899/adrian-lopez> @AdriánLópez,正确的答案是:
UPDATE: Thanks to @janos and @Adrián López, the correct answer is:
from django.db.models import Count
pk_list = [10, 6, 3]
node_query = Node.objects.annotate(count=Count('tags')).filter(count=len(pk_list))
for pk in pk_list:
node_query = node_query.filter(tags__pk=pk)
这篇关于Django查询会获得精确的多重查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!