pythondjangodjango-modelsdjango-adminmodeladmin

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?


I have a Person model that has a foreign key relationship to Book, which has a number of fields, but I'm most concerned about author (a standard CharField).

With that being said, in my PersonAdmin model, I'd like to display book.author using list_display:

class PersonAdmin(admin.ModelAdmin):
    list_display = ['book.author',]

I've tried all of the obvious methods for doing so, but nothing seems to work.

Any suggestions?


Solution

  • As another option, you can do lookups like:

    #models.py
    class UserAdmin(admin.ModelAdmin):
        list_display = (..., 'get_author')
        
        def get_author(self, obj):
            return obj.book.author
        get_author.short_description = 'Author'
        get_author.admin_order_field = 'book__author'
    

    For Django 3.2 or higher, please refer to this answer