我想让表单显示每个帖子的平均评分值。
这是我的模板
<a class="nav-link px-2 text-muted" href="{% url 'posts:post_detail' post.id %}">
<h2>{{ post.school_name }}</h2>
<p>Average rating: {{ post_ratings.get(post=post).avg_rating }}</p>
<p>Автор: {{ post.author }}</p>
<p>Опубликовано: {{ post.created_at }}</p>
<p>Обновлено: {{ post.updated_at }}</p>
<a href="{% url 'posts:post_edit' post.id %}">Редактировать</a>
<a href="{% url 'posts:post_delete' post.id %}">Удалить</a>
</a>
我的观点
def post_list(request):
posts = Post.objects.all()
post_ratings = Comment.objects.values('post').annotate(avg_rating=Avg('score'))
context = {
'posts': posts,
'post_ratings': post_ratings
}
return render(request, 'post_list.html', context)
我的模型class Post(models.Model):
school_name = models.CharField(max_length=200, default='')
country = models.CharField(max_length=200, default='KZ')
city = models.CharField(max_length=200, default='')
content = models.TextField()
website = models.CharField(max_length=200, default='')
your_email = models.EmailField(default='')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
author = models.ForeignKey(User, on_delete=models.CASCADE)
text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
score = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(1)])
def __str__(self):
return self.text
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.post.id)])
为什么我得到这个错误?
我试图改变模板中的行
<p>Average rating: {{ post_ratings.get(post=post.id).avg_rating }}</p>
您不能在模板中直接使用这种python逻辑。在示例中,不能在{{ }}
和{% %}
中使用括号。你可以修改这部分:
<p>Average rating: {{ post_ratings.get(post=post.id).avg_rating }}</p>
<p>Average rating: {{ post.get_avg_rating }}</p>
如果您为Post
模型添加适当的功能:
class Post(models.Model):
# fields
def get_avg_rating(self):
# count and return the result you need for post