Opened 15 years ago
Closed 15 years ago
#13297 closed (duplicate)
Cannot specify 'pk' in model default ordering
Reported by: | anonymous | Owned by: | Filip Gruszczyński |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | 1.1 |
Severity: | Keywords: | ordering pk | |
Cc: | Triage Stage: | Accepted | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
I wanted to make an explicit default ordering over a model's primary key (it does make sense in my app), but manage.py validate complains:
"ordering" refers to "pk", a field that doesn't exist.
Specifying 'id' is fine with it.
Attachments (2)
Change History (7)
comment:1 by , 15 years ago
Triage Stage: | Unreviewed → Accepted |
---|
comment:2 by , 15 years ago
Owner: | changed from | to
---|
I can either change get_field in options to accept pk:
def get_field(self, name, many_to_many=True):
"""
Returns the requested field by name. Raises FieldDoesNotExist on error.
"""
if name == 'pk':
return self.pk
to_search = many_to_many and (self.fields + self.many_to_many) or self.fields
for f in to_search:
if f.name == name:
return f
raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
or check this inside get_validation_errors in django.core.management.validation. I don't know django core that well to decide, which way is better, but it seems to me, that get_field should return some good value also for 'pk'. If someone could make this decision, I will gladly make a patch and write some tests.
comment:3 by , 15 years ago
Proper formatting of the code.
def get_field(self, name, many_to_many=True): """ Returns the requested field by name. Raises FieldDoesNotExist on error. """ if name == 'pk': return self.pk to_search = many_to_many and (self.fields + self.many_to_many) or self.fields for f in to_search: if f.name == name: return f raise FieldDoesNotExist('%s has no field named %r' % (self.object_name, name))
comment:4 by , 15 years ago
I am adding two patches. First changes get_field in options, second changes get_validation_errors in validation. Both also have test (which is only a model with ordering by pk specified). I hope one of them is good, if not, I will be happy to provide something better, if only I am advised what can be fixed in this case.
by , 15 years ago
Attachment: | 13297_1.patch added |
---|
by , 15 years ago
Attachment: | 13297_2.patch added |
---|
comment:5 by , 15 years ago
Resolution: | → duplicate |
---|---|
Status: | new → closed |
This was already reported in the still-open #8291.
Looks like a case where the 'pk' alias isn't being expanded correctly. I'm not sure we specifically document that this *should* be possible, but it would certainly be consistent.