Reputation: 635
I have 3 models -
class A(models.Model):
...
b = models.ManyToManyField(B, related_name="related_a")
class B(models.Model):
...
class Entries(models.Model):
...
b = models.ForeignKey(B, related_name="entries")
I need to loop over all A
objects and show the count of entries
for each b
in A, along with other fields in A. What would be the most efficient way to do it?
Upvotes: 1
Views: 444
Reputation: 5730
You can get it done in 2 queries:
from django.db.models import Count, Prefetch
qs = B.objects.annotate(entry_count=Count('entries'))
a_list = A.objects.prefetch_related(Prefetch('b', queryset=qs))
I hope I've got all related names right. You can access the counts like this:
for a in a_list:
for b_item in a.b:
print(b_item.entry_count)
Upvotes: 1