# Sorting by \<FK\>\_id in admin ChangeList view

**URL:** <https://forum.djangoproject.com/t/sorting-by-fk-id-in-admin-changelist-view/9057>\
**Category:** ORM\
**Created:** [August 2, 2021, 2:14pm UTC](https://forum.djangoproject.com/t/sorting-by-fk-id-in-admin-changelist-view/9057 "2021-08-02T14:14:44Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![djvg](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/djvg/32/5064_2.png) [@djvg](https://forum.djangoproject.com/u/djvg)\
**Post date:** [August 2, 2021, 2:14pm UTC](https://forum.djangoproject.com/t/sorting-by-fk-id-in-admin-changelist-view/9057/1 "2021-08-02T14:14:44Z")

</div>

Recently I noticed that the admin `ChangeList` view does not allow sorting by the `<FK>_id` attribute ([as in ForeignKey.get\_attname](https://github.com/django/django/blob/stable/3.2.x/django/db/models/fields/related.py#L950)) out-of-the-box.

I am aware there are other ways to make this work, as explained in my [recent question](https://forum.djangoproject.com/t/sorting-by-related-id-on-an-admin-change-list-page/9017) 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](https://github.com/django/django/blob/stable/3.2.x/django/contrib/admin/templatetags/admin_list.py#L102)):

```python
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.
