Home > Blockchain >  Django get objects that have certain ManyToMany relations
Django get objects that have certain ManyToMany relations

Time:03-20

suppose we have two models like this:

class User(models.Model):
    name = models.CharField(max_length=255)
    date_joined = models.DateField()
    
class Group(models.Model):
    title = models.CharField(max_length=255)
    users = models.ManyToManyField(User)

we get a queryset of users:

user_qs = User.objects.filter(date_joined__range=['2022-01-01', '2022-01-05'])

how can I get the list of Group objects that have all users of user_qs in their users?

django==3.2

Edit:

I rephrase my question more accurately:

the user_qs gives us some users for example user_1 and user_2. the groups that I want to get must have both user_1 and user_2 in their list of users. if the group has more users besides these two, it is ok and should be included. example:

group_1.users.all() = [user_1, user_2]
group_2.users.all() = [user_1, user_3]
group_3.users.all() = [user_1, user_2, user_3, user_4]
group_4.users.all() = [user_2, user_4]

user_qs = [user_1, user_2]

group_query_should_give = [group_1, group_3]

CodePudding user response:

You can make a set of the Groups, and then check if these all match, with:

from django.db.models import Count

user_qs = User.objects.filter(date_joined__range=['2022-01-01', '2022-01-05'])

Group.objects.filter(
    users__in=user_qs
).alias(
    nusers=Count('users')
).filter(
    nusers=len(user_qs)
)

CodePudding user response:

Group.objects.filter(users__date_joined__range=['2022-01-01', '2022-01-05'])
  • Related