say you have two models like so:
# models.py
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey("Author")
class Author(models.Model):
name = models.CharField(max_length=100)
In this case it would be handy if we could list the author in the list_display of the book admin, but Django gives an error if we list foreign keys like so:
# admin.py
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author__name')
admin.register(Book, BookAdmin)
Luckily we can easily fix this by adjusting how we link into the author foreign key. We just need to add a method to the Book ModelAdmin and return the desired string.
# admin.py
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author_name')
def author_name(self, instance):
return instance.author.name
Be careful though as gratuitous additions of foreign key field can greatly increase the load time of the admin page for the list view of the model: use this judiciously.