How to return exact matches for ManyToMany queries

这一生的挚爱 提交于 2021-01-28 07:14:29

问题


let's say I have a model like

class Group:
    users = ManyToMany(User, related_name='groups')

and I have groups with a different mixture of users

group1 = Group(users=[user1])
group2 = Group(users=[user1, user2])
group3 = Group(users=[user1, user2, user3])

How would I go about querying for groups only with user1 and user2?

I'd like to do something that's like Group.objects.filter(users=[user1, user2]) -> [group2]

but I'm getting TypeError: Field 'id' expected a number but got [<User: user1>, <User: user2>].

if I do Group.objects.filter(user__in=[user1, user2].distinct('id')

it returns back all the groups [group1, group2, group3]

I know how to go through the User instance to get all of the user's groups but I specifically want to go through the Group model.

I imagine I may have to do some type of matching with the ORM... maybe a subquery?


回答1:


You can filter with:

from django.db.models import Count, Q

# since Django-2.0

users = [user1, user2, user3]
users = set(users)

group1 = Group.objects.annotate(
    nusers=Count('users'),
    nuser_match=Count('users', filter=Q(users__in=users))
).filter(
    nusers=len(users),
    nusers_match=len(users)
)

This will thus count the total number of related users, as well as the number of users that match. Both these numbers should equal the number of users in the set.



来源:https://stackoverflow.com/questions/64405615/how-to-return-exact-matches-for-manytomany-queries

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