I've a serializer where I need to set the min and max value. Currently, this is how I do.
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Products
extra_kwargs = {
'amount': {'min_value': 10000, 'max_value': 60000},
}
This works fine, but I don't want to hardcode it, ie I want to fetch it from the DB, just in case the value changes.
I've 2 models.
1) Category
which has min & max value in it.
2) Products
which has amount
and category
as a FK. The amount entered should be within the range of min-max
.
How can this be achieved?
For eg:-
Anything of this sort.
extra_kwargs = {
'amount': {'min_value': Category.min, 'max_value': Category.max},
}
Maybe overriding validate
method is the best option. Because there you have access to the category value.
class ProductSerializer(serializers.ModelSerializer):
def validate(self, data):
category = data['category']
amount = data['amount']
if not (category.min_value < amount < category.max_value):
raise serializers.ValidationError('Invalid amount blah blah blah...')
return data
...
The new version of DRF from 3.5.0 has a fix for this issue,
now you can use max_value
and min_value
in your integer field.
Like this
amount = serializers.IntegerField(required=False, min_value=10000, max_value=60000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With