Django模板未显示注释的值 [英] Django templates are not showing values of annotations
本文介绍了Django模板未显示注释的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想显示与特定房间相关的所有产品的价格总和。
I would like to display price SUM of all products related to particular room.
型号:
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>
不幸的是,总和在页面上不可见。没有错误。我做错了什么?
Unfortunately sums are not visible on the page. There is no error. What i did wrong?
推荐答案
您的视图:
def items(request):
rooms = RoomList.objects.filter(user=request.user).annotate(total_price=Sum('item__price')) # You can filter objects and next add annotates. `annotate(total_price=Sum('item__price')` will add `total_price` to objects.
return render(request, 'items.html', {'items': Item.objects.filter(user=request.user), 'rooms': rooms) # Returns filtered objects with added annotates.
user = request.user),'rooms:rooms)#返回带有添加注释的过滤对象。和模板:
and template:
<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 }}</td> {# Your added annotates #}
</tr>
{% endfor %}
</tbody>
</table>
这篇关于Django模板未显示注释的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文