Django使用完全相同的查询按多对多过滤 [英] Django filter by many to many with exact same query

查看:35
本文介绍了Django使用完全相同的查询按多对多过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在django中是否可以通过查询集或id列表过滤具有多对多关系的对象.以许多相同的值获取查询.模型

Is there any way in django to filter objects with many to many relation by query set or ids list. Get query with exactly same values in many to many. model

class Parent(models.Model):
    name = models.CharField(max_length=1000)
    children = models.ManyToManyField(Child, blank=True)

观看次数

def filter_parents(request):
    children = Child.objects.filter(id__in=[1,2,3])
    parents = Parent.objects.filter(child=child)
    return parents

预期:我正在寻找很多领域中完全相同的孩子的过滤父母

expected: I am looking for filtered parents with exact same children in many to many field

推荐答案

在这种情况下,您可以使用链式过滤.

You can use chain filtering for that case.

from django.db.models import Count

children_id_list = [1, 2, 3]
parents = Parent.objects.annotate(count=Count('children')).filter(count=len(children_id_list))

for child_id in children_id_list:
    parents = parents.filter(children__id=child_id)

或者您可以使用lambda过滤:

Or you can use lambda filtering:

c_id_list = [1, 2, 3]
parents = Parent.objects.annotate(count=Count('children')).filter(count=len(children_id_list))
parents = reduce(lambda p, id: parents.filter(child=id), c_id_list, parents)

或者您可以使用 Q()查询:

from django.db.models import Count, Q

children_id_list = [1, 2, 3]
parents = Parent.objects.annotate(count=Count('children')).filter(count=len(children_id_list))

query = Q()
for child_id in children_id_list:
    query &= Q(children__id=child_id)
parents = parents.filter(query)

结果,您将只获得具有所有子项的所有 Parent 对象,这些对象中的ID列表也不少.

As a result you will get only Parent objects who have all those children in your list of ids only no less no more.

这篇关于Django使用完全相同的查询按多对多过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆