【问题标题】:Django templates are not showing values of annotationsDjango 模板不显示注释的值
【发布时间】: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


    【解决方案1】:

    你的看法:

    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.
    

    和模板:

    <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>
    

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2017-09-22
      • 1970-01-01
      • 2016-03-21
      相关资源
      最近更新 更多