我正在做一个刚刚迁移到django 3.1的项目。我需要删除“将原始列别名传递给QuerySet.order_by()”的用法。但是,我不确定我的项目是否正在使用它。因此,我需要了解“将原始列别名传递给QuerySet.order_by()”的实际工作原理,如果有人能为我提供一个将原始列别名传递给QuerySet.order_by()的代码示例,这将是非常有帮助的。
发布于 2021-09-30 02:02:16
tl;dr:
使用点分隔语法引用表和列的
弃用的运行时检测
首先,检测不推荐使用的模式的最简单方法是使用PYTHONWARNINGS=always或python -Wd运行项目和/或测试套件。如果这样做,您将看到一些有用的警告,可以突出显示错误模式所在的确切行。
例如,当您使用Django 3.1运行我的示例代码时,会出现一个警告:
RemovedInDjango40Warning: Passing column raw column aliases to order_by() is deprecated. Wrap '-auth_user_groups.id' in a RawSQL expression before passing it to order_by().
User.objects.filter(groups__name='teachers').order_by('-auth_user_groups.id')示例-修复错误查询
考虑以下问题-有两个查询,每个查询都将按任期对教师进行排序:
from django.contrib.auth.models import User
from django.db.models.expressions import RawSQL
# Deprecated!
# The value passed to `order_by` references a column on a table
User.objects.filter(groups__name='teachers').order_by('-auth_user_groups.id')
# Safe! We're now using RawSQL to make that same reference.
User.objects.filter(groups__name='teachers').order_by(
RawSQL('auth_user_groups.id', tuple()).desc()
)这两个查询是等效的,并转换为(缩写) SQL:
SELECT auth_user.*
FROM auth_user
INNER JOIN auth_user_groups ON auth_user.id = auth_user_groups.user_id
INNER JOIN auth_group ON auth_user_groups.group_id = auth_group.id
WHERE auth_group.name = 'teachers'
ORDER BY auth_user_groups.id DESC示例-未受影响的查询
不过,大多数查询都不引用表名&使用点分隔语法的列。
这些查询很好,不需要更改:
from django.contrib.auth.models import User
from django.db.models.expressions import RawSQL
# Safe - we're ordering by `auth_user.date_joined`
User.objects.order_by('date_joined')
# Safe - we're ordering by `auth_group.name` after a JOIN on auth_group
User.objects.order_by('groups__name')https://stackoverflow.com/questions/66897125
复制相似问题