How to show different inlines depending of current object field value

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

    Here is a piece of code I wrote when I was faced with the same problem. It is a bit brute force style, I guess, but is very agile and should suit all cases.

    class MyModelAdmin(admin.ModelAdmin):
        def __init__(self, *args, **kwargs):
            super(MyModelAdmin, self).__init__(*args, **kwargs)
            self.inline_instances_hash = {}
            for inline_class in self.inlines:
                for inline_instance in self.inline_instances:
                    if isinstance(inline_instance, inline_class):
                        break
                self.inline_instances_hash[inline_class] = inline_instance
    
        def get_inline_instance(self, inline_class):
            return self.inline_instances_hash[inline_class]
    
        def get_form(self, request, obj=None, **kwargs):
            if obj:
                self.inline_instances = []
                if self.CONDITION:
                    self.inline_instances.append(self.get_inline_instance(
                        THE_INLINE_CLASS_I_WANT))
                #...
            else:
                self.inline_instances = self.inline_instances_hash.values()
    

提交回复
热议问题