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

如何在DRF中重写Serializer的update()方法更新一对一关联的Profile模型

解决方案

要实现仅更新Profile字段且绕过User模型的必填字段验证,你可以通过重写Serializer的update方法+标记User必填字段为只读来完成,具体代码示例如下:

1. 定义Profile嵌套序列化器

先处理Profile模型的字段序列化:

from rest_framework import serializers
from .models import User, Profile

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ['first_name', 'last_name', 'avatar', 'date_of_birth']

2. 重写UserSerializer的update方法

在User序列化器中,将User的必填字段设为只读,同时只处理Profile的更新逻辑:

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ['id', 'phone_number', 'email', 'profile']
        # 标记User的必填字段为只读,避免更新时要求传入
        read_only_fields = ['phone_number', 'email']

    def update(self, instance, validated_data):
        # 提取Profile的更新数据,剩余数据直接丢弃(不更新User)
        profile_data = validated_data.pop('profile', None)
        
        if profile_data:
            # 获取关联的Profile实例
            profile_instance = instance.profile
            # 遍历更新Profile字段
            for attr, value in profile_data.items():
                setattr(profile_instance, attr, value)
            profile_instance.save()
        
        # 直接返回原User实例,不修改User本身字段
        return instance

关键逻辑说明

  • read_only_fields:将User的phone_number和email设为只读后,Serializer在更新时不会验证这两个字段的必填性,自然绕过了必填校验。
  • 重写update方法:只处理传入的profile数据,更新关联的Profile实例,完全不修改User模型的任何字段,确保仅更新Profile内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:05:50