【发布时间】:2011-02-26 08:49:58
【问题描述】:
我需要亲自将投票系统实现到模型中。
首先我得到了 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,它们将计算如何对讨论和回复进行排序。
我将如何实现这两个字段以根据投票对回复和讨论进行排序?
任何帮助都会很棒!
编辑
我在模型中添加了一个名为 vote_difference 的方法
def vote_difference(self):
return int(self.userUpVotes.count()) - int(self.userDownVotes.count())
我可以在我的模板中使用它来获得当前投票,但是我不能在我的 view.py 文件中使用它来按这个值排序,无论如何要在我的视图中包含这个值吗?
编辑(2)
我已经慢慢到达那里,我需要注释 2 个字段并对其进行计算,但是我似乎无法使用注释进行基本的数学计算。
有什么想法吗?
discussions = game.gamediscussion_set.filter(reply_to=None).annotate( score= (Count('userUpVotes') - Count('userDownVotes')) ).order_by('-score')
【问题讨论】:
-
那么你在这方面取得了多大的进步?