|
6 | 6 | from django.core.exceptions import EmptyResultSet, FieldError
|
7 | 7 | from django.db import DatabaseError, NotSupportedError
|
8 | 8 | from django.db.models.constants import LOOKUP_SEP
|
9 |
| -from django.db.models.expressions import OrderBy, Random, RawSQL, Ref, Value |
| 9 | +from django.db.models.expressions import F, OrderBy, Random, RawSQL, Ref, Value |
10 | 10 | from django.db.models.functions import Cast
|
11 | 11 | from django.db.models.query_utils import Q, select_related_descend
|
12 | 12 | from django.db.models.sql.constants import (
|
@@ -361,13 +361,16 @@ def get_order_by(self):
|
361 | 361 | resolved = expr.resolve_expression(self.query, allow_joins=True, reuse=None)
|
362 | 362 | if self.query.combinator:
|
363 | 363 | src = resolved.get_source_expressions()[0]
|
| 364 | + expr_src = expr.get_source_expressions()[0] |
364 | 365 | # Relabel order by columns to raw numbers if this is a combined
|
365 | 366 | # query; necessary since the columns can't be referenced by the
|
366 | 367 | # fully qualified name and the simple column names may collide.
|
367 | 368 | for idx, (sel_expr, _, col_alias) in enumerate(self.select):
|
368 | 369 | if is_ref and col_alias == src.refs:
|
369 | 370 | src = src.source
|
370 |
| - elif col_alias: |
| 371 | + elif col_alias and not ( |
| 372 | + isinstance(expr_src, F) and col_alias == expr_src.name |
| 373 | + ): |
371 | 374 | continue
|
372 | 375 | if src == sel_expr:
|
373 | 376 | resolved.set_source_expressions([RawSQL('%d' % (idx + 1), ())])
|
|
0 commit comments