You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求数据传递至Django Serializer时丢失,求助排查

问题根源

序列化器中包含了user字段,但该字段作为必填的OneToOne关联字段未被设置为只读。即便使用partial=True允许部分更新,DRF序列化器仍会尝试校验user字段的合法性,最终导致请求中的information字段被过滤,无法进入校验和更新流程。

解决方案

1. 修改序列化器,将user设为只读字段

在序列化器的Meta类中添加read_only_fields,明确user字段仅用于序列化输出,不参与更新输入的校验和处理:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ["user", "information"]
        read_only_fields = ["user"]  # 新增此行
    
    def validate(self, attrs):
        print(attrs)  # 现在能正确获取到information字段
        return super().validate(attrs)
    
    def update(self, instance, validated_data):
        print(validated_data)  # 不再是空字典
        # 使用get方法避免KeyError,兼容未传入information的情况
        instance.information = validated_data.get("information", instance.information)
        instance.save()
        return instance

2. 优化视图逻辑(可选)

利用DRF ModelViewSet内置的get_object()方法获取当前用户的Profile,避免手动查询的冗余:

class ProfileView(viewsets.ModelViewSet):
    serializer_class = ProfileSerializer
    queryset = Profile.objects.all()

    def get_object(self):
        # 重写get_object,确保返回当前请求用户的Profile
        return Profile.objects.get(user=self.request.user)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', True)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

3. 修复请求体语法错误(若存在)

你的示例请求体存在语法错误(缺少闭合引号),实际请求需确保JSON格式正确:

JSON.stringify({"information": {"name": "xxx", "birthday": "xxx"}})

原理说明

将user设为只读后,序列化器会忽略该字段的输入校验,仅专注于处理information字段。此时请求中的information数据会被正确解析,进入validate和update方法,完成Profile字段的更新。

内容的提问来源于stack exchange,提问作者Philipp K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 05:01:41