我有一个QuerySet,希望将其传递给通用视图进行分页:
links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300]
这是我的“热门”页面,列出了我最新的300个提交(每页30个链接,共10页)。现在我想按照HackerNews使用的算法对此QuerySet进行排序:
(p - 1) / (t + 2)^1.5
p = votes minus submitter's initial vote
t = age of submission in hours
现在,由于在整个数据库上应用此算法可能非常昂贵,因此我只满足于最近的300次提交。我的网站不太可能成为下一个digg/reddit,因此虽然可扩展性是一个优点,但并非必需。
我的问题是如何迭代查询集并按上述算法进行排序?
更多信息,请参见适用的模型:
class Link(models.Model):
category = models.ForeignKey(Category, blank=False, default=1)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
url = models.URLField(max_length=1024, unique=True, verify_exists=True)
name = models.CharField(max_length=512)
def __unicode__(self):
return u'%s (%s)' % (self.name, self.url)
class Vote(models.Model):
link = models.ForeignKey(Link)
user = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return u'%s vote for %s' % (self.user, self.link)
注:
- 我没有“踩”的选项,所以投票行的存在就是特定用户对特定链接进行了投票的指示。
编辑
我认为我一直在过度复杂化事情,并发现了一个巧妙的小代码片段:
links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300]
for link in links:
link.popularity = ((link.votes - 1) / (2 + 2)**1.5)
但是我却无法将它翻译成我的模板:
{% for link in object_list %}
Popularity: {{ link.popularity }}
{% endfor %}
为什么它没有显示出来?我知道流行度是有效的,因为:
print 'LinkID: %s - Votes: %s - Popularity: %s' % (link.id, link.votes, link.popularity)
在控制台中返回了我预期的结果。
'ValuesListQuerySet' object has no attribute 'sort'
。是我漏掉了哪个导入吗? - TheLizardKingKeyError at /links/ 1
。嗯。 - TheLizardKing