我正在尝试为用户和配置文件模型编写一个嵌套的序列化器,并且我遵循以下示例:

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

    class Meta:
        model = User
        fields = ('username', 'email', 'profile')

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = User.objects.create(**validated_data)
        Profile.objects.create(user=user, **profile_data)
        return user


但是我得到这个错误:

{
    "profile": {
        "user": [
            "This field is required."
        ]
    }
}


我什至尝试将其添加到验证异常中,如下所示:

def get_validation_exclusions(self):
    exclusions = super(ProfileSerializer,
                       self).get_validation_exclusions()
    return exclusions + ['user']


我想我通过添加以下内容解决了这个问题:

user = serializers.ModelField(model_field=Profile()._meta.get_field(
        'user'), required=False)


但是我还不确定。

最佳答案

user中的ProfileSerializer字段设置为只读(或直接删除)

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('user', 'gender', 'phone', ...)
        read_only_fields = ('user',)


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

    class Meta:
        model = User
        fields = ('username', 'email', 'profile')

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        user = User.objects.create(**validated_data)
        Profile.objects.create(user=user, **profile_data)
        return user


保持UserSerializer不变,您将不再收到此错误。

关于python - 用于POST的Django Rest-Framework嵌套序列化器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37330044/

10-12 22:04