Reputation: 105
I am working on a project in django, where I have created a toplist based on the rating given in the reviews. Is there a way I can get the rating of the films showed in the html?
from models.py
class Film(models.Model):
title = models.CharField(max_length=100)
title_short = models.CharField(max_length=17, default=None, null=True)
plot = models.TextField()
poster = models.ImageField(default="default.png", upload_to="posters")
release_date = models.DateField(blank=True, null=True)
date_posted = models.DateTimeField(default=timezone.now)
class Review(models.Model):
writer = models.ForeignKey(User, on_delete=models.CASCADE)
reviewed_film = models.ForeignKey(Film, related_name='reviews', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
rating = models.IntegerField(
default=1, validators=[MinValueValidator(1), MaxValueValidator(5)]
)
def __str__(self): # pragma: no cover
return f"{self.reviewed_film.title} reviewed by {self.writer.username}"
from toplist.html
{% extends "board/base.html" %}
{% block content %}
<h1>Toplist</h1>
{% for film in films %}
<div class="col s12 m7">
<h2 class="header"></h2>
<div class="card horizontal">
<div class="card-image">
<img src="/media/{{film.poster}}">
</div>
<div class="card-stacked">
<div class="card-content">
<h5>{{forloop.counter}}. {{film.title}}</h5>
<p>{{}}/5.0</p>
</div>
<div class="card-action">
<a href="#">Read more</a>
</div>
</div>
</div>
</div>
{% endfor %}
{% endblock content %}
Upvotes: 0
Views: 65
Reputation: 842
You can use annotate
in your queryset. For example:
from django.db.models import Avg
queryset = Film.objects.annotate(total_rating=Avg('reviews_rating'))
and then in your html file
{% for film in films %}
<img src="/media/{{ film.poster }}">
{{ forloop.counter }}. {{ film.title }}
{{ film.total_rating }}/5.0
{% endfor %}
The Documentation has more details.
Upvotes: 2