0
我有幾個類,我想附加到我的模型類作爲Django Rest框架中的嵌套對象。我曾嘗試過「幫助它」,想知道如何將我的課程序列化爲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