【发布时间】:2021-04-15 07:23:10
【问题描述】:
我正在尝试对views.py中的帖子进行排序,从顶部到底部的投票数最多。
这是我目前所拥有的:
在models.py中发布模型
class Post(models.Model):
title = models.CharField("HeadLine", max_length=256, unique=True)
creator = models.ForeignKey(User, on_delete= models.SET_NULL, null=True)
created_on = models.DateTimeField(auto_now_add=True)
url = models.URLField("URL", max_length=256,blank=True)
description = models.TextField("Description", blank=True)
votes = models.IntegerField(null=True)
comments = models.IntegerField(null=True)
def __unicode__(self):
return self.title
def count_votes(self):
self.votes = Vote.objects.filter(post = self).count()
@property
def sort_by_votes(self):
return Vote.objects.filter(post = self).count()
def count_comments(self):
self.comments = Comment.objects.filter(post = self).count()
views.py 中的帖子列表
def NewPostListView(request):
posts = sorted(Post.objects.all(), key=lambda p: p.sort_by_votes, reverse = True)
for post in posts:
post.count_votes()
print(post)
post.count_comments()
context = {
'posts': posts,
}
return render(request,'postlist.html', context)
我正在尝试执行与 posts = Post.objects.all().order_by('count_votes') 等效的操作,但出现“无法解析关键字”错误。到目前为止,使用sorted() 似乎可行,但有时upvote 值不正确。如何获取 QuerySet 以按投票对帖子进行排序?
【问题讨论】:
-
如果投票字段可以多于一个,请使用 Sum():
Post.objects.values("creator").annotate(Count('creator')),sum_votes=Sum('votes')).order_by('sum_votes'). -
要通过降序简单排序添加最小符号“-”:Post.objects.order_by('-votes')。
标签: django sorting django-models