在 Django Admin 中包含来自 OneToOneField 的字段

Including fields from a OneToOneField in Django Admin

我正在尝试将 OneToOneField 中的字段添加到我的管理视图中。这是我的模型外观的示例。

class Customer(BaseUser):
    name = CharField()
    address = CharField()
    secondary_information = OneToOneField("SecondaryCustomerInfo", on_delete=SET_NULL, null=True)


class SecondaryCustomerInfo(models.Model):
    email = EmailField()

我尝试像这样以内联方式添加字段。

class SecondaryCustomerInfoInline(admin.StackedInline):
    model = SecondaryCustomerInfo


class CustomerAdmin(admin.ModelAdmin):
    inlines = [SecondaryCustomerInfoInline]

但是我得到了错误

<class 'user.admin.SecondaryCustomerInfoInline'>: (admin.E202) 'user.SecondaryCustomerInfo' has no ForeignKey to 'user.Customer'.

我习惯于将 OneToOneField 放在次要模型上,但我的同事要求我将它放在主要客户模型上,因为我们将更频繁地访问该信息。我认为改变事情是让我绊倒的原因。我如何将 SecondaryCustomerInfo 中的字段包含在 Customer 的管理视图中?

答案是使用 Django Reverse Admin

来自其文档:

Module that makes django admin handle OneToOneFields in a better way. A common use case for one-to-one relationships is to "embed" a model inside another one. For example, a Person may have multiple foreign keys pointing to an Address entity, one home address, one business address and so on. Django admin displays those relations using select boxes, letting the user choose which address entity to connect to a person. A more natural way to handle the relationship is using inlines. However, since the foreign key is placed on the owning entity, django admins standard inline classes can't be used.

class CustomerAdmin(ReverseModelAdmin):
    inline_type = 'stacked'
    inline_reverse = ['secondary_information']