Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 283
ilse2005 Avatar asked Feb 21 '15 13:02

ilse2005


People also ask

What is partial update in Django?

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).

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

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.


1 Answers

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
like image 50
Mark Chackerian Avatar answered Nov 06 '22 16:11

Mark Chackerian