I have 3 models like:
class Customer(models.Model):
hobby_groups=models.ManyToManyField(
'HobbyGroup',
blank=True,
related_name='group_customers',
)
class HobbyGroup(models.Model):
hobbies = models.ManyToManyField(
'Hobby',
blank=True,
related_name='hobby_groups',
)
class Hobby(models.Model):
title = models.CharField(max_length=255, default='football')
And I need to calculate count of hobbies for each customer.
qs = Customer.objects.annotate(
hobbies_count=Count('hobby_groups__hobbies', distinct=True)
)
With distinct it works fine, but very slow.
I've tried to use Subquery.
hobbies = Hobby.objects.filter(hobby_groups__group_customers=OuterRef('pk')).values('pk')
hobbies_count = hobbies.annotate(count=Count('*')).values('count')
qs = Customer.objects.annotate(
hobbies_count=Subquery(hobbies_count)
)
But it returns exception 'More than one row returned by a subquery used as an expression'
Is there any way to calculate it faster or fix second solution? Because I did similar for backward related models and it worked fine and fast.
Thanks in advance for help.