Recently I noticed that the admin ChangeList
view does not allow sorting by the <FK>_id
attribute (as in ForeignKey.get_attname) out-of-the-box.
I am aware there are other ways to make this work, as explained in my recent question in the “Using Django” category. However, I was wondering whether this was by design, or whether it is simply a feature that has not been implemented yet.
Could anyone shed some light on that?
Perhaps there’s a good reason sorting by <FK>_id
does not work, but, if not, could this be implemented in the future?
A very quick-and-dirty implementation could look like the following (to be inserted into django.contrib.admin.templatetags.admin_list.py):
def result_headers(cl):
...
# Set ordering for attr that is a property, if defined.
if isinstance(attr, property) and hasattr(attr, 'fget'):
admin_order_field = getattr(attr.fget, 'admin_order_field', None)
# START OF ADDITION
elif isinstance(attr, str):
# check if attr represents a foreign key id (<FK>_id)
try:
field = cl.model._meta.get_field(attr)
if hasattr(field, 'attname') and field.attname == attr:
admin_order_field = attr
except FieldDoesNotExist:
pass
# END OF ADDITION
if not admin_order_field:
is_field_sortable = False
...
Please note, I did not run any tests or look for possible side effects. There are probably much better solutions, but the above should give an impression of what I’m after.
Thanks for your help.