Displaying foreign model fields in django admin as editable

给你一囗甜甜゛ 提交于 2021-02-19 11:28:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!