html - 如何将两个 django db 字段的百分比作为模板标签传递
问题描述
我的 django db 中有两个字段,分别称为like
和dislike
. 我想通过我需要将这两个值的平均值传递给要用作的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
解决方案
您可以使用.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">
推荐阅读
- javascript - 按字母顺序对动态生成的表进行排序
- python - Beautiful Soup 基于超链接文本查找 href
- arrays - 使用带空格和多个命令的参数构造命令 bash
- javascript - 在JS中将SVG多个路径合并在一起
- macos - OS X 无法通过自制软件更新 PHP
- r - 为什么应用的函数不适用于 data.table 中的所有行?
- javascript - 通过 Javascript 中的 XMLHttpRequest 访问 cookie 中的访问令牌
- c# - 接近和编码多个类的最佳方式
- wordpress - AWS EC2 上的 wordpress(2 个实例和一个负载均衡器)
- python - 正则表达式 findall 返回子字符串的元组,而不仅仅是字符串