7

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!

3
  • Please mention what do you mean by object level validation? Please post some code to understand clearly. Commented Feb 27, 2015 at 12:42
  • The documentation mentions two types of validation, "field-level" and "object-level". django-rest-framework.org/api-guide/serializers/#validation For the "object-level" validation I need a full object with all fields. So I think it shoudn't be called for partial updates. But is_valid() always fails because of the object level validation Commented Mar 4, 2015 at 14:30
  • I believe django rest framework has a formal solution to this now. Please check django-rest-framework.org/api-guide/serializers/…. Commented Jun 6, 2016 at 17:27

2 Answers 2

14

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.