ilse2005
ilse2005

Reputation: 11429

Django REST Framework Partial update and validation

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!

Upvotes: 7

Views: 20451

Answers (2)

Mark Chackerian
Mark Chackerian

Reputation: 23512

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

Upvotes: 13

Pavel
Pavel

Reputation: 21

You can use the "partial" argument in order to allow partial updates: http://www.django-rest-framework.org/api-guide/serializers/#partial-updates

Upvotes: 0

Related Questions