Please consider some arbitrary model with a foreignkey to another model (in Django 3.2):
class SomeModel(models.Model):
related = models.ForeignKey(to=OtherModel, ...)
We want to show the related_id
(see docs) on the admin change list page, for example:
class SomeModelAdmin(admin.ModelAdmin):
list_display = ['related_id', ...]
Pretty straightforward, but the problem is: we cannot sort by this related_id
column.
Now, there’s at least one way around this, e.g. using admin.display ordering
(or the good old admin_order_field
):
class SomeModelAdmin(admin.ModelAdmin):
list_display = ['display_related_id', ...]
@admin.display(description='related id', ordering='related_id')
def display_related_id(self, obj):
return obj.related_id
Another alternative would be to use list_display = ['related', ...]
, which does allow sorting, then setting OtherModel.__str__
to return the id
, but this may have side effects outside the admin.
Anyway, these workarounds do the job, but they are inconvenient, and the question remains:
Why can we not sort by related_id
out-of-the-box?
Does it have to do with the fact that related_id
is not an actual Field
?