【发布时间】:2014-08-12 01:23:18
【问题描述】:
我想显示与特定房间相关的所有产品的价格总和。
型号:
class Item(models.Model):
product = models.CharField(max_length=150)
quantity = models.DecimalField(max_digits=8, decimal_places=3)
price = models.DecimalField(max_digits=7, decimal_places=2)
purchase_date = models.DateField(null=True, blank=True)
warranty = models.DecimalField(max_digits=4, decimal_places=1)
comment = models.TextField()
room = models.ForeignKey(RoomList)
user = models.ForeignKey(User)
class RoomList(models.Model):
room_name =models.CharField(max_length=150)
user = models.ForeignKey(User)
size = models.DecimalField(max_digits=5, decimal_places=2)
comment = models.TextField()
基于https://docs.djangoproject.com/en/1.6/topics/db/aggregation/#following-relationships-backwards
我创建了视图:
def items(request):
total_price = RoomList.objects.annotate(Sum('item__price'))
return render(request, 'items.html', {'items': Item.objects.filter(user=request.user),
'rooms': RoomList.objects.filter(user=request.user), 'total_price': total_price})
后来我把它推送到模板:
<table class="table table-hover">
<thead>
<tr>
<th>Room name</th>
<th>Costs</th>
</tr>
</thead>
<tbody>
{% for roomlist in rooms %}
<tr>
<td>{{ roomlist.room_name }}</td>
<td>{{ roomlist.total_price.item__price__sum }}</td>
</tr>
{% endfor %}
</tbody>
</table>
很遗憾,页面上看不到总和。没有错误。我做错了什么?
【问题讨论】:
标签: django templates aggregate annotate