django - reddit 风格的 Django 投票

标签 django reddit vote

嘿,我需要手动将投票系统实现到模型中。

我从 Mike DeSimone 那里得到了巨大的帮助,首先完成了这项工作,但我需要扩展他的工作。

这是我当前的代码

查看

def show_game(request):
    game = Game.objects.get(pk=1)
    discussions = game.gamediscussion_set.filter(reply_to=None)
    d = {
        'game':game,
        'discussions':discussions
    }
    return render_to_response('show_game', d)

模板
<ul>
    {% for discussion in discussions %}
    {{ discussion.html }}
    {% endfor %}
</ul>

型号
class GameDiscussion(models.Model):
    game = models.ForeignKey(Game)
    message = models.TextField()
    reply_to = models.ForeignKey('self', related_name='replies', null=True, blank=True)
    created_on = models.DateTimeField(blank=True, auto_now_add=True)
    userUpVotes = models.ManyToManyField(User, blank=True, related_name='threadUpVotes')
    userDownVotes = models.ManyToManyField(User, blank=True, related_name='threadDownVotes')

    def html(self):
        DiscussionTemplate = loader.get_template("inclusions/discussionTemplate")
        return DiscussionTemplate.render(Context({
            'discussion': self,
            'replies': [reply.html() for reply in self.replies.all()]
    }))

讨论模板
<li>
    {{ discussion.message }}
    {% if replies %}
        <ul>
            {% for reply in replies %}
                {{ reply }}
            {% endfor %}
        </ul>
    {% endif %}
</li>

如您所见,我们在模型上有 2 个字段 userUpVotes 和 userDownVotes,它们将计算如何对讨论和回复进行排序。

我将如何实现这 2 个字段来根据投票对回复和讨论进行排序?

任何帮助都会很棒!

编辑

我在我的模型中添加了一个名为 vote_difference 的方法
    def vote_difference(self):
        return int(self.userUpVotes.count()) - int(self.userDownVotes.count())

我可以在我的模板中使用它来获得当前投票,但是我不能在我的 view.py 文件中使用它来按这个值排序,无论如何要在我的 View 中包含这个值?

编辑 (2)

我已经慢慢到达那里了,我需要注释 2 个字段并对其进行计算,但是似乎我无法使用注释进行基本的数学计算。

有任何想法吗?
    discussions = game.gamediscussion_set.filter(reply_to=None).annotate( score= (Count('userUpVotes') - Count('userDownVotes')) ).order_by('-score')

最佳答案

您可能需要考虑通过添加 vote_score 稍微对模型进行非规范化。整数字段。

然后你所要做的就是覆盖 save()使用您的 vote_difference() 计算分数方法。

这使得排序更容易,并且可能会减少您进行的数据库调用次数。

关于django - reddit 风格的 Django 投票,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2950155/

相关文章:

python - Django:模板中的多对多 URL

survey - 验证用户投票一次的民意调查

python - 数字 cargo 市场

php - 有人可以解释 reddit 的 created_utc 以及如何将其转换为 php 中可用的格式

node.js - 使用 NodeJs Request 模块向 Reddit API 发表评论

python - 如何修复禁止的 : received 403 HTTP response in praw?

voting - Facebook基于图像的民意调查

zend-framework - 如果用户对某事进行了投票,您如何存储和显示?

python - CSRF token 丢失或不正确

python - 在 Django 中为 4-D 类型的数组创建模型