计算Django中每位作者的总评论

时间:2017-10-13 09:27:19

标签: python django

我知道有几个关于此的帖子,但没有一个是为我而且为我工作。

基本上,我制作了非常简单的论坛应用,我只想计算其用户名下每CommentsAuthor的总数。{/ p>

models.py [论坛&评论

import datetime
from django.db import models
from django.db.models import Count
from autoslug import AutoSlugField
from app_author.models import Profile

class Forum(models.Model):
    """
    Thread Model
    """
    forum_author = models.ForeignKey(
        Profile,
        related_name='user_forums',
        null=True,
        blank=True,
        on_delete=models.CASCADE
    )

    forum_title = models.CharField(
        max_length=225,
        verbose_name=u'Title',
        blank=False,
        null=False
    )

    ...

    def __str__(self):
        return str(self.forum_title)

    def latest_comment_author(self):
        return self.forum_comments.latest('is_created').comment_author

    def latest_comment_date(self):
        return self.forum_comments.latest('is_created').is_created


class Comment(models.Model):
    """
    Comment Model
    """
    forum = models.ForeignKey(
        'Forum',
        related_name='forum_comments'
    )

    comment_author = models.ForeignKey(
        Profile,
        related_name='user_comments',
        null=True,
        blank=True,
        on_delete=models.CASCADE
    )

    comment_content = MarkdownxField(
        verbose_name=u'Markdown',
    )

    is_created = models.DateTimeField(
        auto_now_add=True,
    )

    is_modified = models.DateTimeField(
        auto_now=True,
        null=True,
        blank=True
    )

    def __str__(self):
        return self.comment_content

Views.py [论坛&评论

def forum_single_view(request, pk):
    """
    Render Single Thread, Comments
    :param request:
    :param pk:
    :return:
    """
    forum = get_object_or_404(Forum, pk=pk)
    forum_comments = Comment.objects.filter(forum=forum.id)
    template = 'app_forum/main/forum_single.html'
    context = {'forum': forum, 'forum_comments': forum_comments}
    return render(request, template, context)

models.py [作者]

class Profile(models.Model):
    """
    Author Model
    """
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE
    )

    ...

模板

{% for comment in forum_comments %}
  ...
{% endfor %

我正在使用类似{{ comment.comment_author.count }}的内容,但它没有显示任何内容。

我知道Aggregation/Annotate,但仍不确定如何使用它来计算我应用中每位作者的总评论数。

谢谢!

0 个答案:

没有答案