【发布时间】:2019-07-02 21:35:30
【问题描述】:
如何在 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? */)
这是相关的分数模型:
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)
所以这个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 值将在新结果中...
【问题讨论】:
-
您使用的是哪个数据库?
-
我正在使用 MySQL
-
你使用的是哪个版本的 django?
-
我使用的是 django 2.1.5
标签: django django-models orm