I want to perform a partial update on my serializer. The problem is that I have a some validation at object level. So the is_valid()
call always fails and I can't save the the updated serializer.
Can I somehow prevent the object level validation on partial updates?
Here a code sample:
class ModelSerializer(serializers.ModelSerializer)
class Meta:
model = A
fields = ('field_b','field_b')
def validate(self,attrs):
if attrs.get('field_a') <= attrs.get('field_b'):
raise serializers.ValidationError('Error')
And in my viewset the partial update method:
class ModelViewSet(viewsets.ModelViewSet):
def partial_update(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.serialize(instance, data=request.data, partial=True)
serializer.is_valid(raise_exception=True)
new_instance = serializer.save()
return Response(serializer.data)
The problem ist that I cannot update 'field_a' without 'field_b'. Thanks for your help!
Generally speaking, partial is used to check whether the fields in the model is needed to do field validation when client submitting data to the view. For example, we have a Book model like this, pls note both of the name and author_name fields are mandatory (not null & not blank).
The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.
self.instance
is how to access the instance in the validator. Here's an example:
def validate_my_field(self, value):
""" Can't modify field's value after initial save """
if self.instance and self.instance.my_field != value:
raise serializers.ValidationError("changing my_field not allowed")
return value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With