I have two models, author and book. an author can have multiple books.
class Author(models.Model):
name = models.CharField(max_length=120, unique=True,
blank=False, null=False)
status = models.TextField(choices=StatusChoices.choices, default=StatusChoices.ACTIVE)
def __str__(self):
return self.name
class Book(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE,
related_name='author_books', null=False)
title = models.CharField(max_length=120, unique=True, blank=False, null=False)
status = models.TextField(choices=StatusChoices.choices, default=StatusChoices.ACTIVE)
def __str__(self):
return self.title
I want to add/edit books inside add/edit author page. For that I implemented tabular inline
class BookInline(admin.TabularInline):
model = Book
fields = ['title', 'id', 'status']
readonly_fields = ['id', 'status']
extra = 1
admin.site.register(Author, AuthorAdmin)
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
list_display = ['author_id', 'author_name', 'books', 'author_status']
fields = ['name', 'id']
readonly_fields = ['id']
search_fields = ['name', ]
list_filter = ['name', 'status']
def author_id(self, obj):
return obj.id
author_id.short_description = 'Author ID'
def author_name(self, obj):
return obj.name
author_name.short_description = 'Author'
def books(self, obj):
return ', '.join([author.title for author in
Book.objects.filter(book_id=obj.id)])
books.short_description = 'Book'
def author_status(self, obj):
return obj.status
author_status.short_description = 'Status'
I want to display all the authors with their respective books in the author list page of django admin site.
I don’t want to display data in books page. I want to display it in authors page.