所以我正在提取一个链接列表,并尝试按受欢迎程度对这些链接进行排序。我正在使用 Hacker News 算法:
Y Combinator's Hacker News: Popularity = (p - 1) / (t + 2)^1.5 Votes divided by age factor. Where p : votes (points) from users. t : time since submission in hours. p is subtracted by 1 to negate submitter's vote. Age factor is (time since submission in hours plus two) to the power of 1.5.factor is (time since submission in hours plus two) to the power of 1.5.
I accomplished this in MySQL and a PHP Framework by using an order by
(SUM(votes.karma_delta) - 1) / POW((TIMESTAMPDIFF(HOUR, links.created, NOW()) + 2), 1.5) DESC
现在我正在使用 PostgreSQL 和 Django。我知道这个确切的 SQL 可能行不通,但我可以稍后进行转换。我遇到的问题是我不知道如何在 Django 中获得如此复杂的 order_by。我的观点有一个完美的:
popular_links = Link.objects.select_related().annotate(karma_total = Sum('vote__karma_delta'))
如果不需要的话,我真的不想通过使用原始 sql 来解决这个问题。
总结一下我的问题:如何在 Django 中创建复杂的 order_by?
编辑
会有分页,我真的只想对我拉的条目进行排序。在 Python 中实际进行排序是否更好?
最佳答案
没有干净的方法,只能将 extra() 与您的自定义 SQL 一起使用:
popular_links = Link.objects.select_related().annotate(karma_total = Sum('vote__karma_delta'))
popular_links = popular_links.extra(
select = {'popularity': '(karma_total - 1) / POW((TIMESTAMPDIFF(HOUR, links.created, NOW()) + 2), 1.5)',},
order_by = ['-popularity',]
)
关于sql - Django 中的复杂排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1964395/