任何人都可以帮助我如何使用**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)
任何人指导我如何使用注解并返回每个对象的注解总数
1条答案
按热度按时间7lrncoxx1#
这是使用
annotate()
的典型示例。我不能100%确定示例中的
published
是什么意思,所以我假设这是objects.filter(status='Published')
的某种快捷方式。