Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 358
Huuuze Avatar asked Oct 02 '08 18:10

Huuuze


1 Answers

As another option, you can do look ups like:

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' 

Since Django 3.2 you can use display() decorator:

class UserAdmin(admin.ModelAdmin):     list_display = (..., 'get_author')          @display(ordering='book__author', description='Author')     def get_author(self, obj):         return obj.book.author 
like image 56
imjoevasquez Avatar answered Oct 11 '22 14:10

imjoevasquez