Home > Enterprise >  Django - PUT endpoint serializer should ignore missing attributing
Django - PUT endpoint serializer should ignore missing attributing

Time:09-27

so I have this put endpoint

def put(self, request):
    user_uuid = get_uuid_from_request(request)
    user_obj = User.objects.get(pk=user_uuid)
    serializer = UpdateUserSerializer(user_obj, data=request.data)

    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)
    else:
        return Response(dict(error=serializer.errors, user_msg=generic_error_message),
                        status=status.HTTP_400_BAD_REQUEST)

with the following serializer

class UpdateUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('given_name', 'middle_name', 'family_name', 'birthdate')

if the incoming request has missing values as in

request.data ={'given_name':'Tom'}

I'd ideally like it to update anything that isn't missing in the current entity. How do I do this? Currently right now when I test it if an attribute is missing it complains.

CodePudding user response:

You can add the flag partial=True to the serializer to support partial updates:

serializer = UpdateUserSerializer(user_obj, data=request.data, partial=True)
  • Related