如何在django中使用annotate()在其他页面上显示评论总数

kse8i1jr  于 2023-06-25  发布在  Go
关注(0)|答案(1)|浏览(118)

任何人都可以帮助我如何使用**annotate()**来显示Django模型中每个对象的评论总数。下面是我的代码。

models.py

class GameArticle(models.Model):
    sno=models.AutoField(primary_key=True)
    status=models.CharField(max_length=10, choices=STATUS, default='Draft')
    uid= ShortUUIDField(help_text='Place for the Article ID ', unique=True, max_length=10, length=5, prefix='ar',alphabet='aBcDeFgHjKlM12345')
    title = models.CharField(max_length=200, help_text='Enter The Article Title')

class GameArticleComment(models.Model):
    sno=models.AutoField(primary_key=True)
    comment=models.TextField()
    user=models.ForeignKey(User, on_delete=models.CASCADE)
    article=models.ForeignKey(GameArticle, on_delete=models.CASCADE, related_name='comments')
    parent=models.ForeignKey('self', on_delete=models.CASCADE, null=True)
    timestamp=models.DateTimeField(default=now)
    class Meta:
        ordering=['-timestamp']

Views.py

def  game_article(request):
    article_list = GameArticle.published.all()
    #............

def article_detail(request, uid):
    data = get_object_or_404( GameArticle, slug=uid,  status='p')
    comments = GameArticleComment.objects.filter(article= get_object_or_404(GameArticle, slug=uid), parent=None)

任何人指导我如何使用注解并返回每个对象的注解总数

7lrncoxx

7lrncoxx1#

这是使用annotate()的典型示例。

from django.db.models import Count

# ...

def game_article(request):
    article_list = GameArticle.published.
            annotate(total_comment_count=Count('comments')).all()
    # ...

我不能100%确定示例中的published是什么意思,所以我假设这是objects.filter(status='Published')的某种快捷方式。

相关问题