Skip to content Skip to sidebar Skip to footer

How To Handle A Patch Request For A Nested Serializer?

I am trying to build an endpoint using Django Rest Framework for the device detail endpoint on http://127.0.0.1:8000/api/v1/controller/device// Models:- Device Model clas

Solution 1:

  1. for your first doubt patch request expects all the fields:

when you are writing instance.organization = validated_data['organization'] you are not checking if the key is actually present or not. so, for that you can do it like validated_data.get('organization'). This represents if you have organization present in validated data then you your variable will be assigned.

you are fetching all the validated data into variables and then you are trying to update it but you can do it easily with this code.

instance = super().update(instance, validated_data)
return instance

This will only update yourfields which is only present in validated_data. It will not update the other fields.

  1. for the second doubt you also want to update the nested serializer fields

you can just get the data from the validated_data and update it.

In this case what you have done is correct and i think it will work perfect.

If you still face any issue, please reply me in this thread i will try to give you answer.

Solution 2:

You can override patch method with partial=True

classDeviceDetailView(RetrieveUpdateDestroyAPIView):
    serializer_class = DeviceDetailSerializer
    queryset = Device.objects.all()
    
    defpatch(self, request, *args, **kwargs):
        kwargs['partial'] = Truereturn self.update(request, *args, **kwargs)

or you can try this method, for this you have to write patch manually https://www.django-rest-framework.org/api-guide/serializers/#partial-updates

# Update `comment` with partial dataserializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True)

Solution 3:

Solution 4:

partial will work here. So it would be like

s = DeviceDetailSerializer(instance, data={'name': 'Manish'}, partial=True)
s.is_valid()
s.save()

If you are hitting the URL with the patch request, it will automatically pass the partial argument.

The only issue I found with your code is

  1. Why you are doing self.Meta.model(**validated_data)? because in update method self.instance would always be there
  2. When you are doing instance.organization = validated_data['organization'], you are not checking whether the key is actually present in validated_data or not. So you need to check first whether the key is present or not and if the key is present only then update the data. For that, you can do if 'organization' in validated_data then do instance.organization = validated_data['organization']

Everything else looks good, If you still face any issue, please update the description with that issue for better understanding.

Post a Comment for "How To Handle A Patch Request For A Nested Serializer?"