Django - 在post_detail模板上显示每个用户的评论计数

时间:2017-09-04 21:27:56

标签: python django django-models django-templates

我的评论设置在哪里,用户可以查看博客帖子,并在post_detail.html模板中显示这些评论。我想在其评论旁边(在任何帖子中)显示每个用户的评论总数。

例如,我希望为每个用户说user 1: 4 comments,依此类推。如果user 1在4个不同的帖子上留下4条评论,则所有4个帖子都应显示user 1: 4 comments

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')

...

def user_rating_count(self):
    user_ratings = Comment.objects.filter(user=2).count()
    return user_ratings

...

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments")
    user = models.ForeignKey(User, related_name="usernamee")
    ...
    review_count = models.IntegerField(default=0)

views.py

@login_required
def add_comment(request, slug):
    post = get_object_or_404(Post, slug=slug)

    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post # Makes the post linked to the comment
            comment.user = request.user # Makes the user linked to the comment
            comment.email = request.user.email
            comment.picture = request.user.profile.profile_image_url()
            comment.review_count = request.user.profile.user_rating_count()
            comment.save()

            return redirect('blog:post_detail', slug=post.slug)
    else:
        form = CommentForm()

    template = "blog/post/add_comment.html"
    context = {'form': form}
    return render(request, template, context)

post_detail.html

...
{% for comment in post.comments.all %}
    {{ comment.review_count }}
{% endfor %}
...

我一直试图通过我的模型的user_rating_count方法来实现这一目标,但我只能手动选择user=1user=2,这有效,但它不是动态的。我试图检索留下评论的用户。

1 个答案:

答案 0 :(得分:0)

<强>尝试:

from django.db.models import Count

def user_rating_count(request):
    users = User.objects.all().annotate(ratings=Count('comment'))
    context={'users':users}
    render(request, 'file.html', context)

现在在 html

{% for user in users %}
    <b>{{user.username}}</b>:{{user.ratings}}
{% endfor %}

这将显示每个用户username : total_comments

您需要通过user_rating_count打电话给urls功能。