How to show different inlines depending of current object field value

前端 未结 6 1445
不知归路
不知归路 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:15

    I realize this question's a bit old and the codebase has changed a bit; there's a cleanish point to override things at now: get_inline_instances. You can do this:

    class MainModelAdmin(models.ModelAdmin):
        inlines = [RelatedModel1InlineAdmin,RelatedModel2InlineAdmin]
    
        def get_inline_instances(self, request, obj=None):
            #Return no inlines when obj is being created
            if not obj:
                return []
            unfiltered = super(MainModelAdmin, self).get_inline_instances(request, obj)
            #filter out the Inlines you don't want
            if obj.type:
                return [x for x in unfiltered if isinstance(x,RelatedModel1InlineAdmin)]
            else:
                return [x for x in unfiltered if isinstance(x,RelatedModel2InlineAdmin)]
    

提交回复
热议问题