首页 > 解决方案 > 如何将两个 django db 字段的百分比作为模板标签传递

问题描述

我的 django db 中有两个字段,分别称为likedislike. 我想通过我需要将这两个值的平均值传递给要用作的width模板<div style="width:x%">

在views.py中:

def PostListView(request):
    posts = Post.objects.all()
    context['posts'] = posts
    return render(request, 'app/mytemplate.html', context)

在模板中:

{% for post in posts %}
   <div class="ratings-css-top" style="width: {% widthratio post.like post.dislike 100 %}">
   </div>
{% endfor %}

如何将字段的平均值作为宽度传递?like % (like + dislike ) * 100

标签: htmldjango

解决方案


您可以使用.annotate()以下命令 [Djanog-doc]查询集:

from django.db.models import F

def PostListView(request):
    posts = Post.objects.annotate(
        total_like=F('like') + F('dislike')
    )
    context['posts'] = posts
    return render(request, 'app/mytemplate.html', context)

Post从此查询集中产生的对象将具有一个额外的属性.total_like,即 和 的.like.dislike。然后我们可以在模板中使用它:

<div style="width: {% widthratio post.like post.total_like 100 %}%"  class="ratings-css-top">

推荐阅读