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 ?