Django 统计多对一关系中特定项数量

1 投票
1 回答
2914 浏览
提问于 2025-04-17 04:01

我有一个Django应用,用户可以发布消息,其他用户可以对这些消息进行投票,类似于Stack Overflow。我在模板中获取“点赞”和“点踩”的数量时遇到了一些问题,希望有人能帮我解决。PostVote和Post类之间是多对一的关系。以下是我的模型:

class Post(models.Model):
    account = models.ForeignKey(Account)
    message = models.CharField(max_length=1024)
    timestamp = models.DateTimeField('post timestamp')

class PostVote(models.Model):
    post = models.ForeignKey(Post)
    account = models.ForeignKey(Account)
    vote = models.CharField(max_length=16, choices=VOTE_CHOICES)
    timestamp = models.DateTimeField('vote timestamp')

这是我获取帖子的方法:

posts = Post.objects.all().order_by('-timestamp')[:10]

我的模板大致是这样的:

{% for post in posts %}
<div>Thumbs up count: {{ WHAT_HERE }}</div>
<div>Thumbs down count: {{ WHAT_HERE }}</div>
{% endfor %}

我该如何在这里获取这些计数呢?我觉得这可能和'annotate'有关,但我一直想不出来。任何帮助都会非常感谢!

1 个回答

2

其实在你的模板里不应该做太多逻辑处理。你可以在你的 Post 模型里添加几个计数的方法:

class Post(models.Model):
    account = models.ForeignKey(Account)
    message = models.CharField(max_length=1024)
    timestamp = models.DateTimeField('post timestamp')

    def upvote_count(self):
        return self.postvote_set.filter(vote=VOTE_CHOICES[0][0]).count()

    def downvote_count(self):
        return self.postvote_set.filter(vote=VOTE_CHOICES[1][0]).count()

然后在你的模板中使用这些方法:

{% for post in posts %}
<div>Thumbs up count: {{ post.upvote_count }}</div>
<div>Thumbs down count: {{ post.downvote_count }}</div>
{% endfor %}

撰写回答