有没有办法将类(对象)序列化为序列化器中的嵌套对象?

时间:2015-12-11 17:01:46

标签: python serialization django-rest-framework

我想将几个类作为Django Rest Framework中的嵌套对象附加到我的模型类中。我试过“帮助它”计算如何使用 repr ()序列化我的类,并且一切都没有运气。有没有办法将我的自定义类实际嵌套到模型表示中作为只读对象?

class WorkflowAction(object):

    def __init__(self):
        self.code = None
        self.name = None
        self.context = None
        self.state_from = None
        self.state_to = None
        self.permission_class = None


class WorkflowDefinition(object):

    def __init__(self, obj):
        self.has_workflow_definition = False
        self.has_workflow = False
        self.workflow_actions = WorkflowAction()
        self._obj = obj

    def __repr__(self):
        _dict = {}
        for item in filter(lambda x: not x.startswith('_') and not callable(getattr(self, x)), dir(self)):
            _dict[item] = getattr(self, item)
        return str(_dict)

这些类作为属性附加到模型对象:

@property
    def workflow_definition(self):
        return WorkflowDefinition(self)

模型序列化器&视图是香草:

class RiskShortSerializer(serializers.ModelSerializer):

    class Meta:
        model = Risk
        fields = (
            'id',
            'project',
            'summary',
            'description',
            'workflow_definition'
        )

class RiskViewSet(viewsets.ModelViewSet):
    queryset = Risk.objects.all()
    serializer_class = RiskShortSerializer

1 个答案:

答案 0 :(得分:0)

您只需要定义嵌套的序列化程序并将其添加为RiskShortSerializer

中的显式字段