在Django中结合prefetch_related和批注 [英] Combine prefetch_related and annotate in Django
本文介绍了在Django中结合prefetch_related和批注的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个模型
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中的数量字段求和。
Instead of counting the number of ModelC objects connected to each ModelB object I want to sum the amount field in ModelC.
我不知道如何将 prefetch_related
和注释
结合在一起queryset,但必须类似于
I don't know how to combine prefetch_related
and annotate
in my queryset, but it must be something like
(ModelA.objects.all()
.prefetch_related('modelb_set', 'groupb_set__modelc_set')
.annotate(total_amount=Sum('modelc_set__amount')))
推荐答案
我认为您应该可以通过以下操作实现这一目标:
I think you should be able to achieve that 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 %}
这篇关于在Django中结合prefetch_related和批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文