Django嵌套序列化器字段-空OrderedDict

pvabu6sv  于 2022-12-05  发布在  Go
关注(0)|答案(2)|浏览(124)

我目前在更新嵌套的序列化程序字段时遇到问题,提供的dict值被丢弃并Map到代码端的空dict
串行器:

class OrganizationSerializer(QueryFieldsMixin, BaseSecuritySerializer):
    class Meta:
        model = Organization
        fields = ("id", "name")
        depth = 0

class UsersSerializer(QueryFieldsMixin, BaseSecuritySerializer):
    organizations = OrganizationSerializer(many=True)

    class Meta:
        model = Users
        fields = '__all__'
        depth = 0

    def update(self, instance: ReportSchedule, validated_data):
        print("validated_data:", validated_data)
        ...

REST请求:方法:贴片

{
    "organizations": [{"id": 10}]
}

打印语句的结果

validated_data: {'organizations': [OrderedDict()]}
pobjuy32

pobjuy321#

这是因为OrganizationSerializer中的“id”字段是只读的,您可以在python www.example.com shell中自己检查它manage.py

test = OrganizationSerializer()
print(repr(test))
toiithl6

toiithl62#

使用上面tempresdisk的方法,序列化程序应该如下所示

OrganizationSerializer():
    id = IntegerField(label='ID', read_only=True)  
    ...

在序列化程序中重写该字段并删除read_only=True应该可以解决这个问题。

class OrganizationSerializer(QueryFieldsMixin, BaseSecuritySerializer):
    id = IntegerField(label='ID')

    class Meta:
        model = Organization
        fields = ("id", "name")
        depth = 0

相关问题