因此,在我的用户详细信息序列化程序中,我有一个嵌套的用户设置序列化程序,除非我为嵌套的序列化程序提供了错误的值,否则它工作正常。如果我尝试通过PUT请求在我的ModelViewSet中使用带有两个错误值的设置来调用更新函数,那么我猜用户设置字段设置为null,因为我遇到以下错误:“ user_settings”:“这是必填栏。”仅在DRF可浏览API中的HTML表单会发生此问题。在JSON中手动将字段设置为false可以正常工作。我还想保留所需的用户设置。
class UserSettingsSerializer(serializers.ModelSerializer):
class Meta:
model = UserSettings
fields = [
"allow_marketing_email",
"allow_notifications"
]
class UserDetailSerializer(UserSerializer):
user_settings = UserSettingsSerializer(required=True)
class Meta(UserSerializer.Meta):
fields = [
...,
"user_settings"
]
def update(self, instance, validated_data):
user_settings_data = validated_data.pop("user_settings")
...
instance.save()
user_settings = instance.user_settings
user_settings.allow_marketing_email = user_settings_data.get(
"allow_marketing_email",
user_settings.allow_marketing_email
)
user_settings.allow_notifications = user_settings_data.get(
"allow_notifications",
user_settings.allow_notifications
)
user_settings.save()
return instance