1

I have model with m2m field users:

class SomeModel(models.Model):
    
    objects = SomeModelManager()

    users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)

My goal is to get instance of this model where set of instance users matches given queryset (it means that every user from queryset should be in m2m relation and no other users).

If I do

obj = SomeModel.objects.get(users=qs)

I get

ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.

And I totaly understand the reason of such error, so the next thing I did was creating a custom Queryset class for this model to override .get() behavior:

class SomeModelQueryset(QuerySet):

    def get(self, *args, **kwargs):
        qs = super()  # Prevent recursion
        if (users := kwargs.pop('users', None)) is not None:
            qs = qs.annotate(count=Count('users__id')).filter(users__in=users, count=users.count()**2)
        return qs.get(*args, **kwargs)


class SomeModelManager(models.Manager.from_queryset(SomeModelQueryset)):
    ...

So what I try to do is to filter only objects with matching users and make sure that amount of users is the same as in queryset.

But I don't like current version of code. users__in adds instance to queryset each time it finds match, so it results in n occurrences for each object (n - number of m2m users for specific object). Count in .annotate() counts unique users ids for each occurrence and then produces single object with all counts combined. So for each object there are n occurrences with count n, and the resulting object will have count n**2.

Is there a way to rewrite this annotate+filter to produce count=n, not n^2 ?

1 Answer 1

1

You can check with an __in filter and then determine the count of the number of users:

from django.db.models import Q

my_users = User.objects.none()  # some queryset of Users
my_users = {user.pk for user in my_users}
obj = SomeModel.objects.alias(
    nusers=Count('users'), nmatch=Count('users', filter=Q(users__pk__in=my_users))
).filter(nusers=len(my_users), nmatch=len(my_users))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.