Serializer 주요 함수 및 활용

DRF Serializer에서 자주 사용되는 핵심 함수들과 데이터 검증 및 변환 활용법

to_representation

직렬화 출력 데이터 커스터마이징. 모델 데이터를 JSON으로 변환할 때 추가 필드나 변환 로직 적용

def to_representation(self, instance):
    representation = super().to_representation(instance)
    representation['likes_count'] = instance.liked_by.count()
    representation['is_favorite'] = instance in self.context['user'].favorites.all()
    return representation

to_internal_value

역직렬화 입력 데이터 전처리. JSON에서 Python 객체로 변환할 때 데이터 정제 및 변환

def to_internal_value(self, data):
    # 불필요한 중첩 데이터 제거
    if 'info' in data:
        data.pop('info')
    return super().to_internal_value(data)

validate

객체 레벨 검증. 여러 필드를 조합한 복합 검증 로직 구현

validate_{field_name}

개별 필드 검증. 특정 필드에 대한 커스텀 검증 로직

save

validated_data를 사용하여 객체 생성/수정

create

새 객체 생성 로직 커스터마이징

update

기존 객체 수정 로직 커스터마이징

validators 속성

필드별 검증 함수 목록 정의

SerializerMethodField

읽기 전용 계산된 필드 추가

get_{field_name}

SerializerMethodField와 함께 사용되는 메서드

Last updated