def update(self, instance: User, validated_data): userprofile_data = validated_data.pop( 'userprofile', {}) # 将 data 中 userprofile 提取 pop 出来,没有就用 {} 代替 instance = super().update( instance, validated_data) # 使用 ModelSerializer 自带的 update if hasattr(instance, 'userprofile'): userprofile = instance.userprofile else: userprofile = UserProfile(user=instance) # 手动更新 userprofile 的每一个值 userprofile.about = userprofile_data.get('about', userprofile.about) userprofile.subscribe_email = userprofile_data.get( 'subscribe_email', userprofile.subscribe_email) userprofile.student_id = userprofile_data.get('student_id', userprofile.student_id) userprofile.save() return instance