유효성검사 4가지
방법
validate_<필드명>
함수를 정의해준다.class MovieSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField()
description = serializers.CharField()
active = serializers.BooleanField()
def create(self, validated_data):
return Movie.objects.create(**validated_data)
# Field-Level Validation
def validate_name(self, value):
if len(value) < 2:
raise serializers.ValidationError('Name is too short!!')
else:
return value
class MovieSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(min_length=2)
description = serializers.CharField()
active = serializers.BooleanField()
# Object-Level Validation
def validate(self, data):
if data['title'] == data['description']:
raise serializers.ValidationError(
'Title and Description should be different')
else:
return data
def name_length(value):
if len(value) < 2:
raise serializers.ValidationError("Name is too short!")
class MovieSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(validators=[name_length])
description = serializers.CharField()
active = serializers.BooleanField()
min_length
파라미터 주기class MovieSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
name = serializers.CharField(min_length=10)
description = serializers.CharField()
active = serializers.BooleanField()