[Fixed]-Django one-to-one fields with User model with using serializer

1👍

You don’t need special serializer for UserProfile if you just want to save UserProfile like that.

Here is a minimal example only using dob field, but the same rules apply to the other fields.

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields =('username','email','password', 'dob')

    def create(self, validated_data):
        dob_data = validated_data.pop('dob')

        user = User.objects.create(
            username=validated_data.get('username'),
            email=validated_data.get('email'),
            password=validated_data.get('password')
        )
        user.set_password(validated_data.get('password'))
        user.save()

        UserProfile.objects.create(user=user, dob=dob_data)
        return user

Leave a comment