[Answered ]-Write a Validator Class in Django-rest-framework that has access to the validatated_data

2👍

The Key for this to work is to use the set_context method for the Django Rest Framework Validator Class in order to gain access to the validated_data. The data will be an attribute on the self.instance when injected into the MyValidator Class below.

http://www.django-rest-framework.org/api-guide/validators/#class-based

Here is the Validator Class:

validators.py:

class MyValidator(object):

    def __init__(self, items, message=None):
        ...

    def __call__(self, kwargs):
        ...

    def set_context(self, serializer):
        """
        This hook is called by the serializer instance,
        prior to the validation call being made.
        """
        # Determine the existing instance, if this is an update operation.
        self.instance = getattr(serializer, 'instance', None)

serializers.py:

class MySerializer(serializers.ModelSerializer):

    class Meta:
        model = MyModel
        validators = [MyValidator('items')]
        fields = (...)

Leave a comment