Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show inline model field in list_display

I have two models:

class Person(models.Model):
    person_name = models.CharField(max_length=255)

    def __unicode__(self):
        return self.person_name

and

class Book(models.Model):
    link = models.ForeignKey(Person)
    book_name = models.CharField(max_length=255)
    book_year = models.CharField(max_length=255)
    book_email = models.CharField(max_length=255)

    def __unicode__(self):
        return self.name

admin.py

class PersonAdmin(admin.ModelAdmin):
    inlines = ('BookInline',)
    list_display = ('person_name', ...)

class BookInline(admin.TabularInline):
    model = Book
    extra = 1
    max_num = 1

In PersonAdmin list_display, how can i show the inline model Book fields (title, name, email).

so when i access Person list of entries in django admin, i see:

person name book name book year book email

like image 593
Ahmad Alzoughbi Avatar asked Feb 08 '23 12:02

Ahmad Alzoughbi


1 Answers

The list_display for the PersonAdmin is meant to display each person once. It doesn't really make sense to include attributes from the book model, because then you would have to include the person multiple times if they have more than one book.

Wouldn't it be better to include the person's name on the book's list_display?

class BookAdmin(admin.ModelAdmin):
    inlines = ('BookInline',)
    list_display = ('person_name', 'book_name', 'book_email', 'book_year')

    def person_name(self, obj):
        return obj.link.person_name

admin.site.register(Book, BookAdmin)
like image 131
Alasdair Avatar answered Feb 24 '23 02:02

Alasdair