Get value of another field in Field level Validation in DRF
I dug around codebase of drf a little bit. You can get values of all fields using following approach. This way you can throw serialization error as {'my_field':'error message}
instead of {'non_field_error':'error message'}
def validate_myfield(self, value):
data = self.get_initial() # data for all the fields
#do your validation
However, if you wish to do it for ListSerializer
, i.e for serializer = serializer_class(many=True)
, this won't work. You will get list of empty values. In that scenario, you could write your validations in def validate
function and to avoid non_field_errors
in your serialization error, you can raise ValidationError
with error message as a dictionary instead of string.
def validate(self, data):
# do your validation
raise serializers.ValidationError({"your_field": "error_message"})
No that is not possible. If you need to access more than one value you have to use the Object-level validation
(see docs):
class Keys_Serializer(serializers.Serializer):
key_id = serializers.IntegerField(required=True)
key_name = serializers.CharField(required=True)
value_id = serializers.IntegerField(required=False)
def validate(self, data):
# here you can access all values
key_id = data['key_id']
value_id = data['value_id']
# perform you validation
if key_id != value_id:
raise serializers.ValidationError("key_id must be equal to value_id")
return data