Django多关联模型注解问题:如何为Asset标注BatchPosition数量总和?
Django注解关联字段求和的问题解决
你的代码存在两个关键错误:
- 多余且错误的
Sum("batch")注解:batch是Asset到Batch的反向关联(默认名为batch_set),不能直接对关联对象执行Sum操作,这个注解完全没必要。 - 字段关联路径错误:要从Asset获取BatchPosition的quantity总和,需要完整的关联链
Asset → Batch → BatchPosition,你既没正确指定反向关联的名称,也没走完整个关联路径。
正确实现方式
情况1:未给Batch的外键设置related_name
Django默认的反向关联名称是模型名小写+_set,Batch对应的反向关联是batch_set,正确代码如下:
from django.db.models import Sum # 为每个Asset注解BatchPosition的quantity总和,字段名为total_quantity Asset.objects.annotate(total_quantity=Sum("batch_set__batchposition__quantity"))
情况2:给Batch的外键设置了related_name
如果修改Batch模型的外键,指定related_name(推荐,让代码更清晰):
class Batch(models.Model): fk_asset = models.ForeignKey(Asset, on_delete=models.CASCADE, blank=False, related_name="batches")
那么代码可以简化为:
from django.db.models import Sum Asset.objects.annotate(total_quantity=Sum("batches__batchposition__quantity"))
补充优化
如果某个Asset没有关联的Batch或BatchPosition,total_quantity会返回None,你可以用Coalesce将其转为0:
from django.db.models import Sum, Value from django.db.models.functions import Coalesce Asset.objects.annotate( total_quantity=Coalesce(Sum("batch_set__batchposition__quantity"), Value(0)) )
内容的提问来源于stack exchange,提问作者Dennis
相关产品推荐
相关产品推荐

