William Afonso
William Afonso

Reputation: 96

Django REST Framework : How to make a custom Validator to validate a combination of several fields at once?

I need to make a custom validator as below. But I can't find any way to retrieve the values of several fields, on which I need to check a condition.

class MyCustomValidator():
    def __call__(self, field_1, field_2):
        if condition_on_field_1_and_field_2 is True:
            message = 'my custom message'
            raise serializers.ValidationError(message)

I saw in the Documentation that there is a way to provide context to a validator. But it seems to provide only one "serializer_field". Is there any way to retrieve more than one serializer field ? How would you do it?

Upvotes: 1

Views: 3347

Answers (1)

atlau
atlau

Reputation: 971

https://www.django-rest-framework.org/api-guide/serializers/#object-level-validation

To do any other validation that requires access to multiple fields, add a method called .validate() to your Serializer subclass. This method takes a single argument, which is a dictionary of field values. It should raise a serializers.ValidationError if necessary, or just return the validated values. For example:

from rest_framework import serializers

class EventSerializer(serializers.Serializer):
    description = serializers.CharField(max_length=100)
    start = serializers.DateTimeField()
    finish = serializers.DateTimeField()

    def validate(self, data):
        """
        Check that start is before finish.
        """
        if data['start'] > data['finish']:
            raise serializers.ValidationError("finish must occur after start")
        return data

Upvotes: 2

Related Questions