0

从这个问题扩展:Django ModelAdmin 中的“list_display”可以显示 ForeignKey 字段的属性吗?,有没有可能做这样的事情:

class MyModelInline(admin.StackedInline):
    model  = MyModel
    extra  = 1
    fields = ('my_field',)

    def my_field(self, obj):
        return obj.one_to_one_link.my_field

如果这样的事情是可能的,它将解决我当前的大部分 Django 问题,但上面的代码不起作用:Django(正确地)抱怨my_field表单中不存在。

4

1 回答 1

1

You can do that, but you must also add my_field to your MyModelInline class's readonly_fields attribute.

fields = ('my_field',)
readonly_fields = ('my_field',)

From the docs:

The fields option, unlike list_display, may only contain names of fields on the model or the form specified by form. It may contain callables only if they are listed in readonly_fields.

If you need the field to be editable, you should be able to do that with a custom form but it takes more work to process it.

于 2013-10-28T23:51:55.717 回答