I am trying to validate some query params in a Django request handler. I am expecting to receive a number n
that's bounded by a range. I'd like to validate n
using rest_framework.serializer
. Something like this:
class NumberSerializer(serializers.Serializer):
number = serializers.FloatField(min_value=1, max_value=10)
However, I'd like to set min_value
and max_value
inside FloatField
dynamically. Is that possible?
I can roll my own validator, but I am trying to learn DRF serializers. So far I feel like DRF serializers have a very specific purpose (validating incoming data against a model), but I want to get into the habit of using serializers for more generic validations like the example above.
CodePudding user response:
You can make custom validate method and min/max value there. For example
def validate_number(self, value):
if value < self.get_min_value():
return ValidationError(...)
return value