问题
I have a Django Model with a Foreign key:
class Library:
name=models.CharField()
class Book:
title=models.CharField()
library=models.ForeignKey(Library)
models.py
class BookAdmin(admin.ModelAdmin):
extra = 0
fields = ['title', 'library__name'] # library__name not found
admin.site.register(Book, BookAdmin)
admin.py
In the admin, I want to display Book
and show an editable field for Library.name
in the Book
view (not the other way around with inlines):
> Book
* Title: "Foo"
* Library Name: "Bar"
As readonly, it's easy (just creating a method in Book model returning the library name value) but I cannot make it work for editable fields, I tried using fields=('title','library.name')
and fields=('title','library__name')
without success
回答1:
You need an inline model admin:
https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects
回答2:
try to use related_name
in models like that
library=models.ForeignKey(Library, related_name="library")
then use fields=('title','library__name')
and it should work.
来源:https://stackoverflow.com/questions/45480778/displaying-foreign-model-fields-in-django-admin-as-editable