django-rest-framework, multitable model inheritance, ModelSerializers and nested serializers

后端 未结 4 2082
小蘑菇
小蘑菇 2020-12-29 07:01

I can\'t find this info in the docs or on the interwebs.
latest django-rest-framework, django 1.6.5

How does one create a ModelSerializer that can handle a nes

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 07:10

    I'm attempting to use a solution that involves different serializer subclasses for the different model subclasses:

    class MyBaseModelSerializer(serializers.ModelSerializer):
    
        @staticmethod
        def _get_alt_class(cls, args, kwargs):
            if (cls != MyBaseModel):
                # we're instantiating a subclass already, use that class
                return cls
    
            # < logic to choose an alternative class to use >
            # in my case, I'm inspecting kwargs["data"] to make a decision
            # alt_cls = SomeSubClass
    
            return alt_cls
    
        def __new__(cls, *args, **kwargs):
            alt_cls = MyBaseModel.get_alt_class(cls, args, kwargs)
            return super(MyBaseModel, alt_cls).__new__(alt_cls, *args, **kwargs)
    
        class Meta:
            model=MyBaseModel
    
    class ModelASerializer(MyBaseModelSerializer):
        class Meta:
            model=ModelA
    
    class ModelBSerializer(MyBaseModelSerializer):
        class Meta:
            model=ModelB
    

    That is, when you try and instantiate an object of type MyBaseModelSerializer, you actually end up with an object of one of the subclasses, which serialize (and crucially for me, deserialize) correctly.

    I've just started using this, so it's possible that there are problems I've not run into yet.

提交回复
热议问题