1

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

angrykoala
  • 3,774
  • 6
  • 30
  • 55
  • Try to do like in [this post answer](https://stackoverflow.com/questions/163823/can-list-display-in-a-django-modeladmin-display-attributes-of-foreignkey-field) – Altynbek Dec 24 '17 at 14:29

2 Answers2

0

You need an inline model admin:

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#inlinemodeladmin-objects

Daniel W.
  • 31,164
  • 13
  • 93
  • 151
-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.

Hossam Salah
  • 185
  • 1
  • 13