Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向Django中的查询集添加注释数_Python_Django_Comments - Fatal编程技术网

Python 向Django中的查询集添加注释数

Python 向Django中的查询集添加注释数,python,django,comments,Python,Django,Comments,我想在Django中显示一篇帖子和评论数。我目前没有帖子模型中的评论数量,我想我可以编写某种模型函数来显示帖子的评论数量,而无需在模型中输入类似于comment\u count的内容 这是我的帖子模型: class Post(models.Model): user = models.ForeignKey(User, unique=False) headline = models.CharField(max_length=400, verbose_name="post headli

我想在Django中显示一篇帖子和评论数。我目前没有帖子模型中的评论数量,我想我可以编写某种模型函数来显示帖子的评论数量,而无需在模型中输入类似于
comment\u count的内容

这是我的帖子模型:

class Post(models.Model):
    user = models.ForeignKey(User, unique=False)
    headline = models.CharField(max_length=400, verbose_name="post headline")
    type = models.CharField(max_length=4)
    branch = models.ForeignKey(Branch, verbose_name="branch name", validators=[branch_exists])
    upvotes = models.IntegerField()
    is_starred = models.BooleanField()
    url_title = models.SlugField()
    creation = models.DateTimeField()
    thumbnail = models.URLField(blank=True)
    body = models.TextField(max_length=90000, blank=False)
    link = models.URLField(blank=False, verbose_name="your link URL")

    def __unicode__(self):
        return u"`%s' posted by %s at %s\n" % (self.headline, self.user, self.creation)
这是我的评论模型:

class Comment(models.Model):
    user = models.ForeignKey(User, unique="False")
    time = models.DateTimeField()
    upvotes = models.IntegerField()
    post = models.ForeignKey(Post, unique="False")
    formatting = models.BooleanField(verbose_name="Format comment?")
    text = models.TextField(max_length=9000, blank=False)
    anonymous = models.BooleanField(verbose_name="Post comment anonymously?")
我想做一些类似的事情:

def __unicode__(self):
    return u"`%s' posted by %s at %s with %s comments" % (self.headline, self.user, self.creation, self.comment_count)

但没有注释\ u计数字段;我希望将评论的数量与帖子一起从数据库中提取。

您可以使用
评论集
属性访问与帖子相关的评论(这是默认值,如果您在
帖子
外键上的
评论
模型上设置了
相关名称
,您可以将其设置为其他内容). 要仅检索计数,请使用
self.comment\u set.count()

Django文档下面有一节介绍这一点。

。。。显然,Django最好保守的秘密是:

from django.db.models import Count
Post.objects.annotate(comment_count=Count('comment'))
然后,每个实例都有一个可以使用的
comment\u count
属性