问题
I would like to display price SUM of all products related to particular room.
Model:
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()
Base on https://docs.djangoproject.com/en/1.6/topics/db/aggregation/#following-relationships-backwards
I created Views:
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})
Later i pushed this to templates:
<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?
回答1:
your view:
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.
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>
来源:https://stackoverflow.com/questions/24341606/django-templates-are-not-showing-values-of-annotations