按 django 中类似挖掘的评级排序
我有两个模型:
class Post(models.Model):
#some fields
pass
class Vote(models.Model):
post = mdoels.ForeignKey(Post)
value = models.IntegerField()
投票值可以是 1 或 -1(用户可以投票赞成或反对)。
我如何获得按评分排序的帖子列表?
I've got two models:
class Post(models.Model):
#some fields
pass
class Vote(models.Model):
post = mdoels.ForeignKey(Post)
value = models.IntegerField()
Votes' value can be either 1 or -1 (user can vote up or down).
How can i get a list of posts, ordered by their rating?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你必须使用注释。 https://docs.djangoproject.com/en/dev/topics/db/ aggregation/
然后您需要导入
Sum
并可以获得按vote_total
排序的帖子列表,例如:编辑:
这是一个例子。创建多个帖子对象和投票对象
然后
posts = Post.objects.annotate(vote_total=Sum('vote__value')).order_by('-vote_total')
将导致[(post. name, post.vote_total) for post in posts]
之中。这有一个问题,因为最后没有帖子。由于 django 的
Sum
聚合函数将没有条目的总和视为 None,而不是 0。如果您最初为每个帖子提供值为 0 的投票(或像 reddit 的系统一样值为 1),则可以解决这个问题,您将没有得到“无”:例如:然后您将得到
编辑:根据有关不同投票类型的评论,将类型添加到投票模型(上面完成)。
您应该能够执行类似的操作(将 'yourappname' 替换为您的应用程序名称以获得正确的数据库表):
现在每个帖子都会有一个
vote_total
以及awesome_total< /code> 和
useful_total
在一次数据库查询中。比 ORM 丑一点,但仍然具有很强的可读性(这就是 Sum 聚合的工作原理。)。您仍然需要对每个类别的投票进行初始投票,以通过无顺序出现的投票。You have to use annotation. https://docs.djangoproject.com/en/dev/topics/db/aggregation/
Then you need to import
Sum
and can get a list of posts ordered by theirvote_total
like:EDIT:
Here's an example. Create several post objects and Vote Objects
Then
posts = Post.objects.annotate(vote_total=Sum('vote__value')).order_by('-vote_total')
will lead to[(post.name, post.vote_total) for post in posts]
being.This has an issue as things with no posts go at the very end. As django's
Sum
aggregation function takes the sum of no entries as None, not 0. This could be solved if you initially gave every post a vote with value 0 (or value 1 like reddit's system), you wouldn't get the None: e.g.:Then you'll get
EDIT: Added type to the Vote model (done above), per comment about different vote types.
You should be able to do something like (replace 'yourappname' with the name of your application to get the right db table):
Now each post now will have a
vote_total
, as wellawesome_total
anduseful_total
in one query to the database. A bit uglier than the ORM, but still quite readable (and this is how the Sum aggregation works. ). You still will have to give each category of votes an initial vote to get past the None appearing out of order.我认为这应该可行:
要反转顺序:
UPDATE
由于 post 是
Post
的ForeignKey
,我们假设您的模型是这样的:所以这应该可行,它将返回名称:
注意_
如果您想使用列表进行查询并出现一些错误,只需将其转换为列表即可:
I think this should work:
To invert the order:
UPDATE
Since post is a
ForeignKey
toPost
, let's assume your model is something like this:So this should work, it would return the names:
note_
If you want to make queries with the list and some error appear, just transform it to a list: