How to show different inlines depending of current object field value

前端 未结 6 1440
不知归路
不知归路 2021-02-14 21:56

Given a model named MainModel and a RelatedModel, where the later has a ForeignKey field to MainModel:

class          


        
6条回答
  •  一生所求
    2021-02-14 22:09

    From peeking at contrib.admin.options.pyLooks like you could override ModelAdmin.get_formsets. Note that the admin site populates self.inline_instances at __init__, so you probably want to follow and not instantiate your inlines over and over. I'm not sure how expensive it is : )

    def get_formsets(self, request, obj=None):
        if not obj:
            return [] # no inlines
    
        elif obj.type == True:
            return [MyInline1(self.model, self.admin_site).get_formset(request, obj)]
    
        elif obj.type == False:
            return [MyInline2(self.model, self.admin_site).get_formset(request, obj)]
    
        # again, not sure how expensive MyInline(self.model, self.admin_site) is. 
        # the admin does this once. You could instantiate them and store them on the 
        # admin class somewhere to reference instead.
    

    The original admin get_formsets uses generators - you could too to more closely mimic the original:

    def get_formsets(self, request, obj=None):
        for inline in self.inline_instances:
            yield inline.get_formset(request, obj)
    

提交回复
热议问题