我想根据一个点域给用户分配排名。在
使用order_by
查询可以很容易地想到。但是如果两个用户的积分相同,需要共享相同的排名,我该如何处理这种情况呢?我应该使用annotate
来查找点数相同的用户吗?在
下面是我当前的代码,以及我想做什么的伪代码描述。在
top_users = User.objects.filter(problem_user=False).order_by('-points_total')
# Wrong - in pseudocode, this should be
# Get the highest points_total, find all the users with that points_total,
# if there is more than one user, set status to 'Joint first prize',
# otherwise set status to 'First prize'
top_users[0].status = "First prize"
if (top_users[1]):
top_users[1].status = "Second prize"
if (top_users[2]):
top_users[2].status = "Third prize"
if (top_users[3]):
top_users[3:].status = "Highly commended"
上面的代码没有处理两个用户积分相同,需要分享二等奖的情况。我想我需要创建一个查询来查找points_total的唯一值,并进行某种嵌套排序?在
它也无法处理这样一个事实:有时用户少于4个——有人知道我如何(在伪代码中)“如果top_users[1]不为null…”在Python中?在
我只需要使用
itertools.groupby
。比如:或者更好的方法是使用
^{pr2}$itertools.count
而不是4个循环:最后一个改进,也许保留一个奖品列表而不是if语句。在
这种方法的警告是,您不是在数据库中进行分组,而是在内存中进行分组。如果有很多用户,这可能是个问题。有关如何在数据库中执行此操作的指导,请参见How to query as GROUP BY in django?。在
快速未经测试的代码,希望您能理解:
欢迎更多优雅的解决方案!在
相关问题 更多 >
编程相关推荐