Well I am building this django rest api where my users can send some data and I save them into the db. There I need to validate the data send by them prior to saving them to the db.
I have already added validators like,
def validate(self, value):
UnitOfMeasureName = ["Each", "Grams", "Ounces", "Pounds", "Kilograms", "Metric Tons"]
if value in UnitOfMeasureName:
return True
else:
return ValidationError('Invalid')
inside the serializers but there are several such validations to be achieved for each serializer. So I am searching for a way where I can use one function for all those validations. I am thinking of using of args
and kwargs
but have no idea how to proceed.
I was thinking something like:
def validate_all(*args, **kwargs):
if not validation_1:
validation_error = {add the error messsage to the dic}
if not validation_2:
...
if not validation_3:
...
return validation_error
An example serializer:
class TransSerializer(serializers.ModelSerializer):
def validate(self, data):
if not data['unitofmeasurename'] in UnitOfMeasureName:
raise serializers.ValidationError("INVALID")
return data
class Meta:
model = Trans
fields = ('unitofmeasurename','name')
So in another serializer I need to check the validation for both 'unitofmeasurename'
and 'name'
. Is there a way to achieve this using only one common function?
Any ideas please. Thanks in advance.