我有三种模式
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()
我可以得到输出name, number of model c objects
==============
Some name, 312
Another name, 17
与查询集ModelA.objects.all().prefetch_related('modelb_set', 'groupb_set__modelc_set')
和模板{% for modela in modela_list %}
{% for modelb in modela.modelb_set.all %}
{{ modelb }}, {{ modelb.modelc_set.count }}
{% endfor %}
{% endfor %}
我不想对连接到每个ModelB对象的ModelC对象的数量进行计数,而是想对ModelC中的数量字段求和。我不知道如何在我的查询集中组合
prefetch_related
和annotate
,但是它一定类似于(ModelA.objects.all()
.prefetch_related('modelb_set', 'groupb_set__modelc_set')
.annotate(total_amount=Sum('modelc_set__amount')))
最佳答案
我认为您应该可以通过执行以下操作来实现:
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')))
在模板中,您应该使用:{% for modela in modela_list %}
{{ modela.name }}, {{ modela.total_amount }}
{% endfor %}
关于django - 在Django中结合prefetch_related和批注,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25386272/