问题描述
我有一个带外键的Django模型:
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
在管理员中,我要显示 Book
,并在 Book 中显示
Library.name
的可编辑字段.代码>视图(与内联相反):
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"
这是只读的,很容易(只是在Book模型中创建一个返回库名值的方法),但是我无法使其适用于可编辑字段,因此我尝试使用 fields =('title','library.name')
和 fields =('title','library__name')
没有成功
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
推荐答案
您需要内联模型管理员:
You need an inline model admin:
https://docs.djangoproject.com/zh/dev/ref/contrib/admin/#inlinemodeladmin-objects
这篇关于在django admin中将外部模型字段显示为可编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!