Fixed #31426 -- Added proper field validation to QuerySet.order_by().

Resolve the field reference instead of using fragile regex based string
reference validation.
This commit is contained in:
Simon Charette 2020-04-05 15:45:06 -04:00 committed by Mariusz Felisiak
parent 98ea4f0f46
commit 513948735b
3 changed files with 19 additions and 19 deletions

View file

@ -30,9 +30,7 @@ from django.db.models.lookups import Lookup
from django.db.models.query_utils import (
Q, check_rel_lookup_compatibility, refs_expression,
)
from django.db.models.sql.constants import (
INNER, LOUTER, ORDER_DIR, ORDER_PATTERN, SINGLE,
)
from django.db.models.sql.constants import INNER, LOUTER, ORDER_DIR, SINGLE
from django.db.models.sql.datastructures import (
BaseTable, Empty, Join, MultiJoin,
)
@ -1895,7 +1893,7 @@ class Query(BaseExpression):
"""
errors = []
for item in ordering:
if isinstance(item, str) and ORDER_PATTERN.match(item):
if isinstance(item, str):
if '.' in item:
warnings.warn(
'Passing column raw column aliases to order_by() is '
@ -1904,6 +1902,18 @@ class Query(BaseExpression):
category=RemovedInDjango40Warning,
stacklevel=3,
)
continue
if item == '?':
continue
if item.startswith('-'):
item = item[1:]
if item in self.annotations:
continue
if self.extra and item in self.extra:
continue
# names_to_path() validates the lookup. A descriptive
# FieldError will be raise if it's not.
self.names_to_path(item.split(LOOKUP_SEP), self.model._meta)
elif not hasattr(item, 'resolve_expression'):
errors.append(item)
if getattr(item, 'contains_aggregate', False):