Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF - Set max and min value of a Serializer field

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},
}
like image 366
PythonEnthusiast Avatar asked Jan 29 '23 07:01

PythonEnthusiast


2 Answers

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

    ...
like image 106
Mohammad Jafar Mashhadi Avatar answered Feb 08 '23 16:02

Mohammad Jafar Mashhadi


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)
like image 22
Espoir Murhabazi Avatar answered Feb 08 '23 17:02

Espoir Murhabazi