I got two Django models linked by a Foreign key:
class Author(models.Model):
...
class Book(models.Model):
author = models.ForeignKey(Author)
Please consider admin example below (I want to do the opposite):
from django.contrib import admin
from my_app.models import Author, Book
class BookInline(admin.TabularInline):
model = Book
class AuthorAdmin(admin.ModelAdmin):
inlines = [
BookInline,
]
admin.site.register(Author, AuthorAdmin)
With this example, we can see in the admin all authors, and for each author, their books.
Now, I would like to to it the other way around. Have en entry per Book in the administration and display the Author informations (it can be readonly) on the Book details. I tried with the solution below, but obviously it didn't work:
from django.contrib import admin
from my_app.models import Author, Book
class AuthorInline(admin.TabularInline):
model = Author
class BookAdmin(admin.ModelAdmin):
inlines = [
AuthorInline,
]
admin.site.register(Book, BookAdmin)
Django raised an error :
<class 'my_app.admin.AuthorInline'>: (admin.E202) 'my_app.Author' has no ForeignKey to 'my_app.Book'.
Do you know how to do that ?
More context :
- Django 1.11
- I want to display Book and Author as full readonly, so the foreign key of the Book will not be changed (at least not from the admin)