我有以下两种模式:
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
使用此列表视图:
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 expression和this stackoverflow post,但无济于事。
答案 0 :(得分:1)
您不需要使用条件聚合,只需要总和
queryset = queryset.annotate(
sum_ = Sum('model_itemtransaction__item_sold')
)