从Listview中的其他模型获取字段的总和

时间:2018-05-14 13:57:15

标签: django

我有以下两种模式:

models.py

class Model_Item(models.Model):
    item_name = models.CharField(max_length = 100, null = False, blank = False, unique = True)

    def __unicode__(self):
        return self.item_name

class Model_ItemTransaction(models.Model):
    item = models.ForeignKey(Model_Item, to_field = "item_name")
    item_sold = models.FloatField(null = True, blank = True)

    def __unicode__(self):
        return self.item

使用此列表视图:

views.py

class View_Item(ListView):
    def get_queryset(self):
        queryset = Model_Item.objects.all()
        queryset = queryset.annotate(
                sum_ = Sum(When(model_itemtransaction__item_sold))
            )
        return queryset

我的目标是获取每个项目的“item_sold”的总值,并在Listview上显示该值。我怎样才能做到这一点?

我一直关注conditional expressionthis stackoverflow post,但无济于事。

1 个答案:

答案 0 :(得分:1)

您不需要使用条件聚合,只需要总和

 queryset = queryset.annotate(
    sum_ = Sum('model_itemtransaction__item_sold')
 )