How to show different inlines depending of current object field value

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

    You need just simply override change_view in ModelAdmin:

    def change_view(self, request, object_id, form_url='', extra_context=None):
        obj = self.model.objects.filter(pk=object_id).first()
        if not obj:
            self.inlines = []
        else:
            if obj.type is True:
                self.inlines = [RelatedModel1InlineAdmin]
            else:
                self.inlines = [RelatedModel2InlineAdmin]
    
        return super().change_view(request,object_id,form_url=form_url,extra_context=extra_context)
    

    that's work for me.

提交回复
热议问题