且构网

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

Django:使用inlineformset进行相关模型的内联编辑

更新时间:2023-02-27 13:11:28

它有点奇怪的回答自己的问题,但没有人加紧。感谢Bernd指出我正确的方向。该解决方案需要制定中介模式。在我的情况下BC类。

Its a bit odd answering your own question, but hey nobody else stepped up. And thanks to Bernd for pointing me in right direction. The solution required making an intermediary model. Class BC in my case.

class A(models.Model):                                        
a = models.IntegerField()                                 


class B(models.Model):                                        
    fb = models.ForeignKey(A)                                 
    b = models.IntegerField()                                 

class C(models.Model):                                        
    fc = models.ForeignKey(B)                                 
    c = models.IntegerField()                                 

class BC(models.Model):                                       
    fc = models.ForeignKey(A)                                 
    fb = models.ForeignKey(B)                                 

而不是在模型管理中使用InlineB A,使用BC内联。所以完整的admin.py看起来像。

And instead of having InlineB in Admin of model A, use inline of BC. So full admin.py looks like.

class InlineC(admin.TabularInline):
    model = C
    extra = 1

class BCInline(admin.TabularInline):
    model = BC
    extra = 1

class AdminA(admin.ModelAdmin):
    fieldsets = [
        (None, {
            'fields': ('a',)
            }),
        ]
    inlines = [BCInline]

class AdminB(admin.ModelAdmin):
    fieldsets = [
        (None, {
            'fields': ('b',)
            }),
        ]
    inlines = [InlineC]

瞧,我得到按钮,用于在A型的添加页面中创建B的完整对象。

And voila, I get button for popus to create full object of B, in the add page of Model A.