How To Handle A Patch Request For A Nested Serializer?
Solution 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.
- 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:
You can pass partial=True
Reference: https://www.django-rest-framework.org/api-guide/serializers/#partial-updates
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
- Why you are doing
self.Meta.model(**validated_data)
? because in update methodself.instance
would always be there - When you are doing
instance.organization = validated_data['organization']
, you are not checking whether thekey
is actually present invalidated_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 doif 'organization' in validated_data
then doinstance.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?"