Karina Klinkevičiūtė
Karina Klinkevičiūtė

Reputation: 1538

Django Rest-Framework nested serializer for POST

I'm trying to write a nested serializer for User and Profile models and I'm following this example:

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

But Im getting this error:

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

I even tried to add it to validation exceptions, like this:

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

I think I solved it by adding this:

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

But I'm not sure yet.

Upvotes: 3

Views: 2732

Answers (1)

Lucas Weyne
Lucas Weyne

Reputation: 1152

Set user field from ProfileSerializer as read-only (or simply remove)

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

Leave the UserSerializer intact and you will not getting this error any more.

Upvotes: 3

Related Questions