【问题标题】:Django model - how to add order index annotation?Django模型-如何添加订单索引注释?
【发布时间】: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


【解决方案1】:

几个月前我做过类似的工作。我使用 postgres 作为数据库和 django 2.0。我不确定以下代码是否能解决您的问题。但我想分享我的部分代码来解决我的问题。

from django.db.models import Window, F
from django.db.models.functions import DenseRank

 ranklist = Score.objects.annotate(
            place=Window(
                expression=DenseRank(),
                order_by=[
                    F('points').desc(),
                ]))

【讨论】:

  • 非常感谢!这正是我正在寻找的,它对我非常有效!
猜你喜欢
  • 2010-10-17
  • 1970-01-01
  • 2014-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多