Serializer:
class ProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('foo', 'bar') class UserSerializer(serializers.ModelSerializer): userprofile = ProfileSerializer(partial=True) class Meta: model = User fields = ('username', 'password', 'email', 'userprofile') def create(self, validated_data): profile_data = validated_data.pop('userprofile') user = User.objects.create(**validated_data) UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('userprofile') profile = instance.userprofile instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.save() profile.foo = profile_data.get('foo', profile.foo) profile.bar = profile_data.get('bar', profile.bar) profile.save() return instance
View:
class UsersViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,)
Both creations and updates work very well, the problem is with partial updates. The django user model has the required username, and I would like to make this optional. Is there a way to enable partial updates for this scenario?
For example, I would like to update with the help of PUT only "foo".
zerg. source share