showing a foreign key value in a django admin list display Nov

say you have two models like so:


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:


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.


class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author_name')

    def author_name(self, instance):

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.

Bookmark and Share
blog comments powered by Disqus