Mongoengine RF的DynamicDocumentSerializer在另一个文档中创建一个文档

时间:2018-08-08 22:51:38

标签: django mongoengine

我正在努力解决以下问题。我定义了一个简单的模型及其相应的序列化器,如下所示:

models.py

class Device(mongoengine.DynamicDocument):
    data = mongoengine.fields.DictField()
    meta = {
        'queryset_class': DeviceQuerySet,
        'ordering': ['-data.date']
    }

serializers.py

    from rest_framework_mongoengine import serializers as mongoserializers

    class DeviceSerializer(mongoserializers.DynamicDocumentSerializer):
        with open(SCHEMA_PATH, 'r') as fschema:
            schema_data = fschema.read()
        schema = json.loads(schema_data)

        def validate(self, data):       
            jsonschema.validate(data, self.schema)
            return data

        def create(self, validated_data):
            return TestResult.objects.create(**validated_data)

        class Meta:
            model = Device
            fields = '__all__'

我希望我的文档是可扩展的,也就是说,我可以在必要时向其中添加一些新字段,这与模型上的数据字段相同,但是另一方面,我需要检查是否存在某些基本字段数据字典存在。这就是验证部分的原因。

我的控制器(即视图)如下所示:

views.py

class DeviceView(viewsets.ModelViewSet):
    lookup_field = 'id'
    serializer_class = DeviceSerializer

    def create(self, request):
        serializer = self.serializer_class(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
            serializer.save(data=request.data)
        except djongo.sql2mongo.SQLDecodeError:
            return Response(
                {"Error": "Database is unreachable"},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )
        except jsonschema.ValidationError as err:
            return Response(
                {"Error": str(err)},
                status=status.HTTP_403_FORBIDDEN
            )

        return Response(
            status=status.HTTP_200_OK
        )

问题在于,写在数据库(MongoDB)中的json(文档)看起来如下:

{
    "_id": ObjectId("5b6afd49540d1c2233b9e775")
    "field1": "value1",
    "field2": "value2",
--------more fields here--------
    "data": {
        "field1": "value1",
        "field2": "value2",
--------more fields here--------
     }
    "some_specific_param": "some_value",
    "one_more_specific_param": "one_more_value"
}

字段data几乎满足了我的所有需求(我之所以说是因为我也在使用_id和添加到主文档中的两个其他参数),但是数据嵌套的dict字段在其外部重复。我希望我的文档看起来像这样:

{
    "_id": ObjectId("5b6afd49540d1c2233b9e775")
    "data": {
        "field1": "value1",
        "field2": "value2",
--------more fields here--------
     }
    "some_specific_param": "some_value",
    "one_more_specific_param": "one_more_value"
}

我在做什么错?如何避免这种序列化器行为?

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以通过在Serializer的Meta类中将 exclude 字段指定为

class DeviceSerializer(mongoserializers.DynamicDocumentSerializer):
    # your code

    class Meta:
        model = Device
        exclude = ('field1', 'field2')