如何在 django 中注释查询集,以添加表示排序结果中每行的索引(位置)的附加字段?
我需要以有序的方式检索用户,并添加一个字段,该字段将指定订单中每个对象的绝对位置。
这就是我的代码:
users = User.objects.all().annotate(total_points=Sum('score_earnings', distinct=True)).order_by('-total_points')
users = users.annotate(place, /* how to get an index of each ordered? */)
这是相关的 Scores 模型:
class Score(models.Model):
user = models.ForeignKey('users.CustomUser', related_name='score_earnings', on_delete=models.CASCADE)
points = models.DecimalField(max_digits=8, decimal_places=1)
So this place
字段应表示结果中每行的索引:1, 2, 3, ...
稍后我将不得不从结果中选择一个范围并期望获得以下值place
字段绝对值:
users[3:6]
预期结果:
[{
"total_points": 100.0,
"place": 3
}, {
"total_points": 70.0,
"place": 4
}, {
"total_points": 50.0,
"place": 5
}]
我正在使用 MySQL 数据库。
- - - - - - 更新 - - - - - -
我能够在 SQL 中执行类似的操作:
set @row_num = 0;
SELECT name, @row_num := @row_num + 1 as row_index
FROM Users
但这仍然不完全是我需要的,因为如果我添加 LIMIT 语句,row_index 值将在新结果内......