Is it possible to order the Admin panel by a FK?

I use ordering = ['...'] to sort my model data within the admin panel.

Is it possible to sort by a foreignKey?


Have you tried it?

Also, see the docs for list_display.

You’re asking if I’ve tried something I don’t know the steps needed to try?

Also, if I tried and succeded, why ask?

Yes, I tried random things with zero insight. I am here seeking insight on how to achieve.

I will look at the link.

1 Like

Because you might have tried and failed - in which case it would be extremely useful to see what you tried, and then to figure out what why it didn’t work.

No, that only leads us down the road of trying to cram in possibly flawed method. It is much better to start again and ask for the proper method. This situation isn’t trying to fix code logic, it is about finding out the proper methd to achieve something built into django.

list_display isn’t what I am asking about. I am asking about ordering the model data. Which is done with ordering = ['..'].

list_display lets you add columns. I am talking abut sorting the data within the columns.

And if you read through that section, you’ll see that it discusses the use of the ordering attribute and how it applies to the list_display, and what all you can do with that attribute.

Here is the solution. I just found it on SO and tested.
I decided to search for - show foreign key in list display. Because I knew I’d get more hits and once I had the FK in my list_display - I could order by it.

class QuotesAdmin(admin.ModelAdmin):
    list_display = ('quote_id', 'mission', 'get_mission')
    @admin.display(ordering='missions__mission_no', description='Column Title')
    def get_mission(self, obj):
        return obj.mission.mission_no

What got me at first was - on the last line - it wants the column / variable. Not the model Class name.

You’ve already found a solution, but I’d just like to chime in and say that you can add this sorting to any custom field in the same way, even sorting on a column of the foreign key relationship. Basically, anything you can stuff inside ”order_by”.

If you need to sort by non-column data, like things produced by ”annotate”, that’s also possible.