如何为drf中的字段延迟加载嵌套的序列化程序类?

时间:2017-05-31 13:57:48

标签: python django serialization django-rest-framework

如何创建一个具有如下对象的Generic对象:

{
    "_type": "A",
    "content_object": {
      "a's_field": "something..",
    }
}

并创建一个Generic对象,它具有如下所示的B对象:

{
    "_type": "B",
    "content_object": {
      "b's_field": "something else..",
      "b's_field_2": "something else.."
    }
}

serializers.py

class ContentObjectSerializer(serializers.Serializer):

    def to_representation(self, value):
        """
        Serialize A instances using a A serializer,
        and B  instances using a B serializer.
        """

        if isinstance(value, A):
            serializer = ASerializer(value)
        elif isinstance(value, B):
            serializer = BSerializer(value)
        else:
            raise Exception('Unexpected type of tagged object')

        return serializer.data

    def to_internal_value(self, data):

        _type = self.parent.initial_data.get("_type", None)
        if not _type:
            return None

        context = self.parent.context
        if _type == "A":
            serializer = ASerializer(context=context)
        elif _type == "B":
            serializer = BSerializer(context=context)

        return serializer.to_internal_value(data)


class GenericSerializer(ModelSerializer):
    content_object = ContentObjectSerializer()

    class Meta:
        model = Generic
        fields = ("_type", "content_object", )

    def create(self, validated_data):
        # question = validated_data.pop("content_object")
        # is an ordered dictionary & not a dictionary
        # because of the below reason:
        # my guess is that parent serializer's save calls create,
        # passing validated_data
        # validations are performed and
        # validated_data is obtained from to_internal_value
        # and converted to dict

models.py

class Generic(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

views.py

class GenericViewSet(ModelViewSet):
    serializer_class = GenericSerializer
    permission_classes = (IsAuthenticated,)
    queryset = Generic.objects.all()

我需要一种使用相同端点创建不同模型对象的方法。

0 个答案:

没有答案