Reputation: 330
I have two fields in my django db which called like
and dislike
. I want to pass I need to pass the average of these two values to the template to be used as the width
of <div style="width:x%">
.
in views.py:
def PostListView(request):
posts = Post.objects.all()
context['posts'] = posts
return render(request, 'app/mytemplate.html', context)
and in template:
{% for post in posts %}
<div class="ratings-css-top" style="width: {% widthratio post.like post.dislike 100 %}">
</div>
{% endfor %}
how to pass this average value of fields as a width? like % (like + dislike ) * 100
Upvotes: 1
Views: 113
Reputation: 476584
You can .annotate()
[Djanog-doc] the queryset with:
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)
The Post
objects that arise from this queryset will have an extra attribute .total_like
that is the sum of .like
and .dislike
. We can then use this in the template:
<div style="width: {% widthratio post.like post.total_like 100 %}%" class="ratings-css-top">
Upvotes: 1