且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django Admin:OneToOne 关系作为内联?

更新时间:2023-02-08 19:49:57

完全可以将内联用于 OneToOne 关系.但是,定义关系的实际字段必须位于内联模型上,而不是父模型上 - 与 ForeignKey 的方式相同.切换它,它会工作.

It's perfectly possible to use an inline for a OneToOne relationship. However, the actual field defining the relationship has to be on the inline model, not the parent one - in just the same way as for a ForeignKey. Switch it over and it will work.

评论后编辑:您说父模型已经向管理员注册:然后取消注册并重新注册.

Edit after comment: you say the parent model is already registered with the admin: then unregister it and re-register.

from original.satchmo.admin import ProductAdmin

class MyProductInline(admin.StackedInline):
    model = MyProduct

class ExtendedProductAdmin(ProductAdmin):
    inlines = ProductAdmin.inlines + (MyProductInline,)

admin.site.unregister(Product)
admin.site.register(Product, ExtendedProductAdmin)


2020 年更新(Django 3.1.1)

此方法仍然有效,但新 Django 版本中的某些类型已更改,因为现在应该将 ExtendedProductAdmin 中的 inlines 添加为列表而不是元组,像这样:

This method is still working but some types has changed in new Django version since inlines in ExtendedProductAdmin should now be added as list and not tuple, like this:

class ExtendedProductAdmin(ProductAdmin):
    inlines = ProductAdmin.inlines + [MyProductInline]

否则你会得到这个错误:

Or you will get this error:

    inlines = ProductAdmin.inlines + (MyProductInline,)
TypeError: can only concatenate list (not "tuple") to list