Django queryset get exact manytomany lookup [duplicate]

自作多情 提交于 2019-11-27 20:12:10
stalk

One approach is to use chain of filters:

node_query = Node.objects.all()
pk_list = [10, 6, 3]

for pk in pk_list:
    node_query = node_query.filter(tags=pk)

Now node_query will match node, that has at least three tags with pk 10, 6, 3. To exact matching of three tags:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!