1
0
mirror of https://github.com/django/django.git synced 2025-10-26 15:16:09 +00:00

Fixed #34421 -- Fixed QuerySet.update() on querysets in descending order by annotations.

This commit is contained in:
hb6h057
2023-03-17 00:03:32 +08:00
committed by Mariusz Felisiak
parent d2b688b966
commit 2ffa815c73
3 changed files with 24 additions and 1 deletions

View File

@@ -108,6 +108,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):
"update.tests.AdvancedTests."
"test_update_ordered_by_inline_m2m_annotation",
"update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation",
"update.tests.AdvancedTests.test_update_ordered_by_m2m_annotation_desc",
},
}
if self.connection.mysql_is_mariadb and (

View File

@@ -1190,11 +1190,18 @@ class QuerySet(AltersData):
# Inline annotations in order_by(), if possible.
new_order_by = []
for col in query.order_by:
if annotation := query.annotations.get(col):
alias = col
descending = False
if isinstance(alias, str) and alias.startswith("-"):
alias = alias.removeprefix("-")
descending = True
if annotation := query.annotations.get(alias):
if getattr(annotation, "contains_aggregate", False):
raise exceptions.FieldError(
f"Cannot update when ordering by an aggregate: {annotation}"
)
if descending:
annotation = annotation.desc()
new_order_by.append(annotation)
else:
new_order_by.append(col)