Merge prefetch_related and annotate in Django

I have three models

class ModelA(models.Model):
    name = CharField(max_length=100)

class ModelB(models.Model):
    modela = ForeignKey(ModelA)

class ModelC(models.Model):
    modelb = ForeignKey(ModelB)
    amount = IntegerField()

I can get a conclusion

name, number of model c objects
==============
Some name, 312
Another name, 17

With request

ModelA.objects.all().prefetch_related('modelb_set', 'groupb_set__modelc_set')

and pattern

{% for modela in modela_list %}
    {% for modelb in modela.modelb_set.all %}
        {{ modelb }}, {{ modelb.modelc_set.count }}
    {% endfor %}
{% endfor %}

Instead of counting the number of ModelC objects associated with each ModelB, I want to summarize the quantity field in ModelC.

I do not know how to combine prefetch_relatedand annotatemy set of queries, but it should be something like

ModelA.objects.all().prefetch_related('modelb_set', 'groupb_set__modelc_set').annotate(total_amount=Sum('modelc_set__amount'))
+4
source share
1 answer

I think you can achieve this by doing this:

from django.db.models import F, Sum

ModelA.objects.all()\
    .prefetch_related('modelb_set', 'modelb__modelc_set')\
    .values('name')\ # group values by modela.name, read: https://docs.djangoproject.com/en/1.9/topics/db/aggregation/
    .annotate(name = F('name'),
              total_amount = Sum('modelb__modelc__amount'))

and in your template you should use:

{% for modela in modela_list %}
    {{ modela.name }}, {{ modela.total_amount }}
{% endfor %}
+1
source

All Articles