I checked it when I made the app, so I will write it so that I can call it when I forget it.
In Django, I used to put a clean method in the form for validation, but I thought that Django REST Framework would write custom validation in the first place, so I investigated it.
Write each validation in seliarizers.py
.
Write as follows.
#Validate for adults
def validate_age(age):
if age < 21:
raise serializers.ValidationError('It's too early for minors!')
In class base, write using the __call__
method.
In addition, since it is highly reusable on a class basis, if you basically use this, the visibility of the code will be better.
class AgeValidator(object):
def __init__(self,num):
self.num = num
def __call__(self,age):
if age < self.num:
message = 'This page is for Adult!'
raise serializers.ValidationError(message)
Recommended Posts