Skip to content

Commit

Permalink
refactored field errors for invalid or non-existing ordering
Browse files Browse the repository at this point in the history
  • Loading branch information
PirosB3 committed Aug 9, 2014
1 parent 375a7ec commit 2b7a588
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 22 deletions.
42 changes: 22 additions & 20 deletions django/db/models/base.py
Expand Up @@ -1441,28 +1441,30 @@ def _check_ordering(cls):

# Skip ordering on pk. This is always a valid order_by field
# but is an alias and therefore won't be found by opts.get_field.
fields = (f for f in fields if f != 'pk')
fields = set(f for f in fields if f != 'pk')

for field_name in fields:
try:
cls._meta.get_field(field_name, m2m=False)
except FieldDoesNotExist:
if field_name.endswith('_id'):
try:
field = cls._meta.get_field(field_name[:-3], m2m=False)
except FieldDoesNotExist:
pass
else:
if field.attname == field_name:
continue
errors.append(
checks.Error(
"'ordering' refers to the non-existent field '%s'." % field_name,
hint=None,
obj=cls,
id='models.E015',
)
# Check for invalid or non existing field ordering.
invalid_fields = []

# Any field name that is not present in field_names
# Does not exist.
all_field_names = set(cls._meta.field_names)
invalid_fields.extend(fields - all_field_names)

# Any field that is a m2m field should not be allowed
# ordering
m2m_field_names = set(f.name for f in cls._meta.get_fields(data=False, m2m=True))
invalid_fields.extend(fields & m2m_field_names)

for invalid_field in invalid_fields:
errors.append(
checks.Error(
"'ordering' refers to the non-existent field '%s'." % invalid_field,
hint=None,
obj=cls,
id='models.E015',
)
)
return errors

@classmethod
Expand Down
4 changes: 2 additions & 2 deletions django/db/models/sql/query.py
Expand Up @@ -1417,7 +1417,7 @@ def names_to_path(self, names, opts, allow_many=True, fail_on_missing=False):
return path, final_field, targets, names[pos + 1:]

def raise_field_error(self, opts, name):
available = opts.field_names + list(self.aggregate_select)
available = list(opts.field_names) + list(self.aggregate_select)
raise FieldError("Cannot resolve keyword %r into field. "
"Choices are: %s" % (name, ", ".join(sorted(available))))

Expand Down Expand Up @@ -1651,7 +1651,7 @@ def add_fields(self, field_names, allow_m2m=True):
# from the model on which the lookup failed.
raise
else:
names = sorted(opts.field_names + list(self.extra)
names = sorted(list(opts.field_names) + list(self.extra)
+ list(self.aggregate_select))
raise FieldError("Cannot resolve keyword %r into field. "
"Choices are: %s" % (name, ", ".join(names)))
Expand Down

0 comments on commit 2b7a588

Please sign in to comment.