DRF - Validation

강재구·2021년 7월 3일
1

Django REST Framework

목록 보기
3/3

유효성검사

유효성검사 4가지 방법

  • Field Level
  • Object Level
  • Validator
  • 옵션주기

Field Level Validator

  • 필드 단위의 유효성검사가 필요할때,
  • 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

Object Level Validator

  • 객체 수준에서의 유효성 검사가 필요할때,
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

Validator

  • 유효성검사기를 따로 만들기
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()
profile
Python Backend Developer @Fitpet

0개의 댓글