Django : Inline editing of related model using inlineformset

荒凉一梦 提交于 2019-12-23 02:31:43

问题


I'm still stuck with the inline Tree-like-eiditing of related models on same page. I've got three models, A, B and C.

Class A

Class B
    fb = foreignkey(A)

Class C
    fc = foreignkey(B)

In admin.py I'm doing something like

AdminA
    inlines = [inlineB]

AdminB
    inlines = [inlineC]

I want that when I edit/add model A, I should be able to add ModelB inline, and add Model B's related Model C entries. I was trying out inlineformsets, but can't find out how to use them for my purpose. Moreover, I found this old discussion on same problem. But again, since I'm new to Django, I don't know how to make it work.


回答1:


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)                                 

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]

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



来源:https://stackoverflow.com/questions/3881323/django-inline-editing-of-related-model-using-inlineformset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!