我想在 Django 中显示帖子以及评论数。我目前没有帖子模型中的评论数量,我想我可以编写某种模型函数来显示帖子有多少评论,而无需在comment_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)
但没有 comment_count 字段;我希望将评论的数量与帖子一起从数据库中提取。