为什么 django-rest-framework(使用带 mongodb 的 django-nonrel)在更新实例时设置为空子对象 PK

Why django-rest-framework (using django-nonrel with mongodb) sets to null child objects PKs when updating an instance

任何包含嵌入式模型的对象实例都会发生这种情况。 当我尝试更新父实例时,它会将其子 PK 设置为空。

这是已更新的 json 对象的摘录:

{
"pk": "558d023d153bd41930b3fcf0",
"checkgroup_id": "checkgroupid 5",
"name": "checkgroup five",
"description": "this an example description",
"control_config": {
    "control_config_1": {
        "pk": null,
        "params": {
            "param2": {
                "pk": null,
                "value": "value2",
                "mandatory": false,
                "default": "default"
            },
            "param1": {
                "pk": null,
                "value": "value1",
                "mandatory": false,
                "default": "default"
            }
        },
        "exceptions": {
            "exception1": {
                "pk": null,
                "description": "description example",
                "params": [
                    {
                        "pk": null,
                        "value": "value1",
                        "mandatory": false,
                        "default": "default"
                    },
                    {
                        "pk": null,
                        "value": "value2",
                        "mandatory": false,
                        "default": "default"
                    }
                ]
            }
        }
    }
},

这是模特:

class CheckGroup(models.Model):
"""It defines a set of controls to be applied. """
    checkgroup_id = models.TextField(max_length=250)
    name = models.TextField(max_length=250)
    description = models.TextField(max_length=250)
    control_config = DictField(EmbeddedModelField(ControlConfig))
    controls = DictField(EmbeddedModelField(Control))

其序列化程序定义为:

class CheckGroupSerializer(serializers.ModelSerializer):
""" Transforms CheckGroup into json
"""
control_config =  serializers.DictField(child=ControlConfigSerializer())
controls = serializers.DictField(child=ControlSerializer())
pk = serializers.CharField()

class Meta:
    """ It lets to choose the model that will be serialize and its         fields
    """
    model = CheckGroup
    fields = ('pk', 'checkgroup_id', 'name', 'description', 'control_config', 'controls')

好吧,我在 django-rest-framework 文档上找到了原因。 问题是框​​架没有处理,应该由我们来实现。

文档说:

Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default ModelSerializer .create() and .update() methods do not include support for writable nested representations.