我正在django中做一个项目,在那里我根据评论中给出的评级创建了一个toplist。有没有办法获得html中显示的电影的评级?与 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}"从排行榜.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 %}
1 回答
浮云间
TA贡献1829条经验 获得超4个赞
您可以在查询集中使用。例如:annotate
from django.db.models import Avg
queryset = Film.objects.annotate(total_rating=Avg('reviews_rating'))
,然后在您的 html 文件中
{% for film in films %}
<img src="/media/{{ film.poster }}">
{{ forloop.counter }}. {{ film.title }}
{{ film.total_rating }}/5.0
{% endfor %}
本文档包含更多详细信息。
添加回答
举报
0/150
提交
取消