mongo模型的序列化器,不包括特定的相关类类型

时间:2014-12-28 18:32:51

标签: serialization django-rest-framework mongoengine

考虑以下模型:

class Line(Document):
    name = StringField()

class Root(Document):
    name = StringField()
    children = ListField(fields=ReferenceField('RootContent'))

class RootContent(Document):
    meta = { 'allow_inheritance': True }

class Directory(RootContent):
    name = StringField()
    children = ListField(fields=ReferenceField('RootContent'))

class File(RootContent):
    name = StringField()
    children = ListField(fields=ReferenceField('Line'))

我需要一个使用django-rest-framework-mongoengine的序列化程序,它可以为我提供所有目录和文件的根,但不是行。我可以设置一个相当大的“深度”值。如何编写一个序列化程序来完成它?

1 个答案:

答案 0 :(得分:0)

最后我最终做了以下的事情:

from rest_framework_mongoengine import serializers as mongo_serializers

class ChildField(mongo_serializers.serializers.Serializer):
    def to_native(self, value):
        return self.parent.to_native(value)

class TreeSerializer(mongo_serializers.MongoEngineModelSerializer):
    name = mongo_serializers.fields.SerializerMethodField(method_name='get_name')
    children = ChildField(many=True)

    class Meta:
        model = Root

    def get_name(self, obj):
        """Mainly in to nullify children of 
        object"""
        if isinstance(obj, File):
            obj.children = []
        return obj.name