본문 바로가기
Django/Django REST framework

10. Serializer fields

by hyun-am 2021. 7. 16.

Form 클래스의 각 필드는 데이터의 유효성을 검사할 뿐만 아니라 데이터를 "정리"하여 일관된 형식으로 정규화합니다.

시리얼라이저 필드는 기본 값과 내부 데이터 유형 간의 변환을 처리합니다. 또한 입력 값의 유효성을 검사하고 상위 개체에서 값을 검색하고 설정하는 작업도 처리합니다.

참고 : 시리얼라이저 필드는 fields.py에 선언되어 있지만 규칙에 따라 from rest_framework import serializers 를 사용하여 필드를 가져와야 하며 필드를 serializers.<FieldName>으로 참조해야합니다.

Core arguments

각 시리얼라이저 필드 클래스 생성자는 최소한 이러한 아규먼트를 사용합니다. 일부 Field 클래스는 추가 필드별 아규먼트를 사용하지만 다음과 같은 내용들은 항상 허용되어야 합니다.

read_only

읽기 전용 필드는 API 출력에 포함되지만 create 또는 update 작업 중에는 입력에 포함되어서는 안됩니다. 시리얼라이저 입격에 잘못 포함된 모든 'read_only' 필드는 무시됩니다.

표현을 직렬화할 때 필드가 사용되지만 역직렬화 중에 인스턴스를 생성하거나 업데이트할 때는 사용되지 않도록 하려면 이것을 True로 설정하면됩니다.

기본값은 False입니다.

write_only

인스턴스를 업데이트하거나 생성할 때 필드가 사용될 수 있지만 표현을 직렬화할 때 포함되지 않도록 하려면 이것을 True로 설정하면 되겠습니다.

required

일반적으로 역직렬화 중에 필드가 제공되지 않으면 오류가 발생합니다. 역직렬화 중에 이 필드가 필요하지 않은 경우 false로 설정합니다.

이를 False로 설정하면 인스턴스를 직렬화할 때 객체 속성 또는 딕셔너리 키를 출력에서 생략할 수도 있습니다. 키가 없으면 단순히 출력 표현에 포함되지 않습니다.

기본값은 True입니다.

default

설정하면 입력 값이 제공되지 않은 경우 필드에 사용할 기본값을 제공합니다. 설정하지 않으면 기본 동작은 속성을

부분 업데이트 작업 중에는 기본값이 적용되지 않습니다. 부분 업데이트의 경우 들어오는 데이터에 제공된 필드만 검증된 값이 반환됩니다.

함수 또는 기타 callable로 설정될 수 있으며, 이 경우 값이 사용될 때 마다 evaluate됩니다. 호출될 때 아규먼트를 받지 않습니다. callable에 required_context = True 속성이 있으면 시리얼라이저 필드가 아규먼트로 전달됩니다. 예시는 다음과 같습니다.

class CurrentUserDefault:
    """
    May be applied as a `default=...` value on a serializer field.
    Returns the current user.
    """
    requires_context = True

    def __call__(self, serializer_field):
        return serializer_field.context['request'].user

인스턴스를 직렬화할 때 개체 속성 또는 딕셔너리 키가 인스턴스에 없으면 기본값이 사용됩니다.

기본값을 설정하면 필드가 필요하지 않음을 의미합니다. default 및 required 키워드 아규먼트를 모두 포함하는 것은 유효하지 않으며 오류가 발생합니다.

allow_null

일반적으로 None이 시리얼라이저 필드에 전달되면 오류가 발생합니다. None을 유효한 값으로 간주해야 하는 경우 이 키워드 아규먼트를 True로 설정하면 되겠습니다.

명시적 기본값 없이 이 아규먼트를 True로 설정하면 직렬화 출력에 대한 기본값이 null임을 의미하지만 입력 역직렬화에 대한 기본값을 의미하지는 않습니다.

기본값은 False입니다.

source

필드를 채우는 데 사용할 속성의 이름입니다. URLField(source='get_absolute_url')와 같이 self 아규먼트만 사용하는 메서드이거나 EmailField(source='user.name')와 같은 특성을 순회하기 위해 점으로 구분된 표기법을 사용할 수 있습니다. 점 표기법으로 필드를 직렬화할 때 애트리뷰트 순회 동안 객체가 없거나 비어 있으면 기본값을 제공해야 할 수 있습니다.

source='*' 값은 특별한 의미를 가지며 전체 개체가 필드로 전달되어야 함을 나타내는 데 사용됩니다. 이것은 중첩 표현을 결정하기 위해 전체 개체에 액세스해야 하는 필드에 유용할 수 있습니다.

기본값은 필드 이름입니다.

validators

입력해야 하는 input 필드에 적용해야 하고 유효성 검사 오류를 발생시키거나 단순히 반환하는 벨리데이터 함수 목록입니다. 벨리데이터 함수는 일반적으로 serializers.ValidationError를 발생시켜야 하지만 Django 코드베이스 또는 써드파티 Django 패키지에 정의된 벨리데이터와의 호환성을 위해 Django의 내장 ValidationError도 지원됩니다.

error_messages

에러 메세지를 딕셔너리 형태로 보여줍니다.

label

HTML form 필드 또는 기타 설명 요소에서 필드 이름으로 사용할 수 있는 짧은 텍스트 문자열입니다.

help_text

HTML form 필드 또는 기타 설명 요소에서 필드에 대한 설명으로 사용할 수 있는 텍스트 문자열입니다.

initial

HTML form 필드의 값을 미리 채우는 데 사용해야 하는 값입니다. 일반 Django 필드와 마찬가지로 callable을 전달할 수 있습니다.

import datetime
from rest_framework import serializers
class ExampleSerializer(serializers.Serializer):
    day = serializers.DateField(initial=datetime.date.today)

 

style

렌더러가 필드를 렌더링해야 하는 방법을 제어하는 데 사용할 수 있는 키-값 쌍의 딕셔너리입니다.

여기에 있는 두 가지 예는 'input_type' 및 'base_template'입니다.

# Use <input type="password"> for the input.
password = serializers.CharField(
    style={'input_type': 'password'}
)

# Use a radio input instead of a select input.
color_channel = serializers.ChoiceField(
    choices=['red', 'green', 'blue'],
    style={'base_template': 'radio.html'}
)

Boolean fields

BooleanField

boolean 표현입니다.

HTML로 인코딩된 form 인풋을 사용할 때 default=True 옵션이 지정된 경우에도 값을 생략하면 항상 필드를 False로 설정하는 것으로 처리된다는 점에 유의하면 됩니다.

HTML 체크박스 인풋은 값을 생략하여 체크되지 않은 상태를 나타내므로 DRF는 생략을 빈 체크박스 인풋으로 처리하기 때문입니다.

Django 2.1은 models.BooleanField에서 blank kwarg를 제거했습니다. Django 2.1 models.BooleanField 필드 이전에는 항상 blank=True였습니다. 따라서 Django 2.1 기본 Serializers.BooleanField 인스턴스는 필수 kwarg 없이 생성되기 때문에 (즉, reuired=True와 동일) Django의 이전 버전에서는 기본 BooleanField 인스턴스가 required=False 옵션으로 생성됩니다. 이 동작을 수동으로 제어하려면 시리얼라이저 클래스에서 BooleanField를 명시적으로 선언하거나 extra_kwargs 옵션을 사용하여 필요한 flag를 설정하면 됩니다.

django.db.models.fields.BooleanField에 해당합니다.

Signature : BooleanField()

NullBooleanField

None도 유효한 값으로 받아들이는 Boolean 표현식 입니다.

django.db.models.fields.NullBooleanField에 해당합니다.

Signature : NullBooleanField()

String fields

CharField

텍스트 표현입니다. 선택적으로 텍스트가 max_length보다 짧고 min_length보다 긴지 확인합니다.

Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField.

Signature: CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)

  • max_length - 인풋값이 max_length보다 작은지 확인합니다.
  • min_length - 인풋값이 max_length보다 큰지 확인합니다.
  • allow_blank - True로 설정되면 빈 문자열이 유효한 값으로 간주되어야 합니다. False로 설정하면 빈 문자열이 유효하지 않으므로 반드시 값을 입력해 주어야 합니다. 기본값은 False입니다.
  • trim_whitespace - True로 설정하면 선행 및 후행 공백이 잘립니다. 기본값은 True입니다.

allow_null 옵션은 문자열 필드에도 사용할 수 있지만 allow_blank를 사용하는 것은 권장되지 않습니다. allow_blank=True 및 allow_null=True 둘 다 설정하는 것이 유효하지만 이렇게 하면 문자열 표현에 혀용되는 두 가지 다른 유형의 null 값이 있게 되어 데이터 불일치와 미묘한 애플리케이션 버그가 발생할 수 있습니다.

EmailField

텍스트가 유효한 이메일 주소인지 확인합니다.

Corresponds to django.db.models.fields.EmailField

Signature: EmailField(max_length=None, min_length=None, allow_blank=False)

RegexField

텍스트가 주어진 특정 정규표현식과 일치하는지 확인합니다.

Corresponds to django.forms.fields.RegexField.

Signature: RegexField(regex, max_length=None, min_length=None, allow_blank=False)

정규표현식 아규먼트는 문자열이거나 컴파일된 파이썬 정규표현식 개체일 수 있습니다.

유효성 검사를 위해 Django의 django.core.validators.RegexValidator을 사용합니다.

SlugField

[a-zA-Z0-9_-]+.패턴에 대해 입력의 유효성을 검사합니다.

Corresponds to django.db.models.fields.SlugField.

Signature: SlugField(max_length=50, min_length=None, allow_blank=False)

URLField

URL 일치 패턴에 대해 입력의 유효성을 검사하는 RegexField입니다. http://<host>/<path> 형식의 정규화된 URL이 필요합니다.

Corresponds to django.db.models.fields.URLField. Uses Django's django.core.validators.URLValidator for validation.

Signature: URLField(max_length=200, min_length=None, allow_blank=False)

UUIDField

입력이 유효한 UUID 문자열인지 확인하는 필드입니다. to_internal_value 메서드는 uuid.UUID 인스턴스를 반환합니다. 출력시 필드는 표준 하이픈 형식의 문자열을 반환합니다.

"de305d54-75b4-431b-adb2-eb6b9e546013"

Signature: UUIDField(format='hex_verbose')

  • format: Determines the representation format of the uuid value
    • 'hex_verbose' - The canonical hex representation, including hyphens: "5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
    • 'hex' - The compact hex representation of the UUID, not including hyphens: "5ce0e9a55ffa654bcee01238041fb31a"
    • 'int' - A 128 bit integer representation of the UUID: "123456789012312313134124512351145145114"
    • 'urn' - RFC 4122 URN representation of the UUID: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" Changing the format parameters only affects representation values. All formats are accepted by to_internal_value

FilePathField

파일 시스템의 특정 디렉토리에 있는 파일 이름으로 선택이 제한된 필드입니다.

Corresponds to django.forms.fields.FilePathField.

Signature: FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)

  • path - The absolute filesystem path to a directory from which this FilePathField should get its choice.
  • match - A regular expression, as a string, that FilePathField will use to filter filenames.
  • recursive - Specifies whether all subdirectories of path should be included. Default is False.
  • allow_files - Specifies whether files in the specified location should be included. Default is True. Either this or allow_folders must be True.
  • allow_folders - Specifies whether folders in the specified location should be included. Default is False. Either this or allow_files must be True.

IPAddressField

입력이 유효한 IPv4 또는 IPv6 문자열인지 확인하는 필드입니다.

Corresponds to django.forms.fields.IPAddressField and django.forms.fields.GenericIPAddressField.

Signature: IPAddressField(protocol='both', unpack_ipv4=False, **options)

  • protocol Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive.
  • unpack_ipv4 Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'.

Numeric fields

IntegerField

인테저필드입니다.

Corresponds to django.db.models.fields.IntegerField, django.db.models.fields.SmallIntegerField, django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField.

Signature: IntegerField(max_value=None, min_value=None)

  • max_value Validate that the number provided is no greater than this value.
  • min_value Validate that the number provided is no less than this value.

FloatField

플로팅 포인트 필드입니다.

Corresponds to django.db.models.fields.FloatField.

Signature: FloatField(max_value=None, min_value=None)

  • max_value Validate that the number provided is no greater than this value.
  • min_value Validate that the number provided is no less than this value.

DecimalField

A decimal representation, represented in Python by a Decimal instance.

Corresponds to django.db.models.fields.DecimalField.

Signature: DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)

  • max_digits The maximum number of digits allowed in the number. It must be either None or an integer greater than or equal to decimal_places.
  • decimal_places The number of decimal places to store with the number.
  • coerce_to_string Set to True if string values should be returned for the representation, or False if Decimal objects should be returned. Defaults to the same value as the COERCE_DECIMAL_TO_STRING settings key, which will be True unless overridden. If Decimal objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting localize will force the value to True.
  • max_value Validate that the number provided is no greater than this value.
  • min_value Validate that the number provided is no less than this value.
  • localize Set to True to enable localization of input and output based on the current locale. This will also force coerce_to_string to True. Defaults to False. Note that data formatting is enabled if you have set USE_L10N=True in your settings file.
  • rounding Sets the rounding mode used when quantising to the configured precision. Valid values are [decimal module rounding modes](https://docs.python.org/3/library/decimal.html#rounding-modes). Defaults to None.

사용 예시

소수점 이하 2자리의 resolution로 최대 999까지의 숫자를 검증하는 예시

serializers.DecimalField(max_digits=5, decimal_places=2)

소수점 이하 10자리의 resolutiuon로 10억 미만의 숫자를 검증하려면

serializers.DecimalField(max_digits=19, decimal_places=10)

이 필드는 선택적 인수인 coerce_to_string도 사용합니다. True로 설정하면 표현이 문자열로 출력됩니다. False로 설정하면 표현은 Decimal 인스턴스로 남고 최종 표현은 렌더러에 의해 결정됩니다.

설정하지 않으면 기본적으로 COERCE_DECIMAL_TO_STRING 설정과 동일한 값이 되며, 달리 설정하지 않는 한 True입니다.

Date and time fields

DateTimeField

A date and time representation.

Corresponds to django.db.models.fields.DateTimeField.

Signature: DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None)

  • format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python datetime objects should be returned by to_representation. In this case the datetime encoding will be determined by the renderer.
  • input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATETIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].
  • default_timezone - A pytz.timezone representing the timezone. If not specified and the USE_TZ setting is enabled, this defaults to the current timezone. If USE_TZ is disabled, then datetime objects will be naive.

DateTimeField format strings.

문자열 포맷은 포맷을 명시적으로 지정하는 Python strftime 형식이거나 ISO 8610 스타일 날짜 시간을 사용해야 함을 나타내는 특수 문자열 'iso-8601'일 수 있습니다.(예 : '2013-01-29T12:34:56.000000Z')

None 값이 형식에 사용되면 to_representaion에 의해 날짜/시간 객체가 반환되고 최종 출력 표현은 렌더러 클래스에 의해 결정이 됩니다.

auto_now and auto_now_add model fields

ModelSerializer 또는 HyperlinkedModelSerializer를 사용할 때 auto_now=True 또는 auto_now_add=True인 모델 필드는 기본적으로 read_only=True인 직렬 변환기 필드를 사용합니다.

이 동작을 재정의하려면 시리얼라이저에서 DateTimeField를 명시적으로 선언해야합니다. 예시는 다음과 같습니다.

class CommentSerializer(serializers.ModelSerializer):
    created = serializers.DateTimeField()

    class Meta:
        model = Comment

DateField

A date representation.

Corresponds to django.db.models.fields.DateField

Signature: DateField(format=api_settings.DATE_FORMAT, input_formats=None)

  • format - A string representing the output format. If not specified, this defaults to the same value as the DATE_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python date objects should be returned by to_representation. In this case the date encoding will be determined by the renderer.
  • input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the DATE_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].

DateField format strings

문자열 포맷은 포맷을 명시적으로 지정하는 Python strftime 형식이거나 ISO 8610 스타일 날짜 시간을 사용해야 함을 나타내는 특수 문자열 'iso-8601'일 수 있습니다.예('2013-01-29')

TimeField

A time representation.

Corresponds to django.db.models.fields.TimeField

Signature: TimeField(format=api_settings.TIME_FORMAT, input_formats=None)

  • format - A string representing the output format. If not specified, this defaults to the same value as the TIME_FORMAT settings key, which will be 'iso-8601' unless set. Setting to a format string indicates that to_representation return values should be coerced to string output. Format strings are described below. Setting this value to None indicates that Python time objects should be returned by to_representation. In this case the time encoding will be determined by the renderer.
  • input_formats - A list of strings representing the input formats which may be used to parse the date. If not specified, the TIME_INPUT_FORMATS setting will be used, which defaults to ['iso-8601'].

TimeField format strings

문자열 포맷은 포맷을 명시적으로 지정하는 Python strftime 형식이거나 ISO 8610 스타일 날짜 시간을 사용해야 함을 나타내는 특수 문자열 'iso-8601'일 수 있습니다. 예시('12:34:56.000000')

DurationField

A Duration representation. Corresponds to django.db.models.fields.DurationField

The validated_data for these fields will contain a datetime.timedelta instance. The representation is a string following this format '[DD] [HH:[MM:]]ss[.uuuuuu]'.

Signature: DurationField(max_value=None, min_value=None)

  • max_value Validate that the duration provided is no greater than this value.
  • min_value Validate that the duration provided is no less than this value.

Choice selection fields

ChoiceField

제한된 선택 셋에서 값을 허용할 수 있는 필드입니다.

해당 모델 필드에 선택=... 아규먼트가 포함된 경우 ModelSerializer에서 자동으로 필드를 생성하는 데 사용합니다.

Signature: ChoiceField(choices)

  • choices - A list of valid values, or a list of (key, display_name) tuples.
  • allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
  • html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
  • html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"

allow_blank와 allow_null은 모두 ChoiceField에서 유효한 옵션이지만 둘 다 사용하지 않고 하나만 사용하는 것이 좋습니다. 텍스트 선택에 대해서는 allow_blank가 우선되어야 하고 숫자 또는 기타 텍스트가 아닌 선택에 대해서는 allow_null이 우선되어야 합니다.

MultipleChoiceField

제한된 선택 셋에서 선택한 0, 하나 또는 여러 값 셋을 허용할 수 있는 필드입니다. 단일 필수 인수를 사용합니다. to_internal_value는 선택한 값을 포함하는 집합을 반환합니다.

Signature: MultipleChoiceField(choices)

  • choices - A list of valid values, or a list of (key, display_name) tuples.
  • allow_blank - If set to True then the empty string should be considered a valid value. If set to False then the empty string is considered invalid and will raise a validation error. Defaults to False.
  • html_cutoff - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to None.
  • html_cutoff_text - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to "More than {count} items…"

ChoiceField와 마찬가지로 allow_blank 및 allow_null 옵션이 모두 유효하지만 둘 다 사용하지 않고 하나만 사용하는 것이 좋습니다. 텍스트 선택에 대해서는 allow_blank가 우선되어야 하고 숫자 또는 기타 텍스트가 아닌 선택에 대해서는 allow_null이 우선되어야 합니다.

File upload fields

Parsers and file uploads.

FileField 및 ImageField 클래스는 MultiPartParser 또는 FileUploadParser와 함께 사용하는 경우에만 적합합니다. 대부분의 파서는 예를 들어 JSON은 파일 업로드를 지원하지 않습니다. Django의 일반 FILE_UPLOAD_HAMDLERS는 업로드된 파일을 처리하는 데 사용됩니다.

FileField

파일 representation입니다. Django의 표준 FileField 유효성 검사를 수행합니다.

Corresponds to django.forms.fields.FileField.

Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

  • max_length - Designates the maximum length for the file name.
  • allow_empty_file - Designates if empty files are allowed.
  • use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.

ImageField

이미지 representation입니다. 업로드된 파일 콘텐츠가 알려진 이미지 형식과 일치하는지 확인합니다.

Signature: ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

  • max_length - Designates the maximum length for the file name.
  • allow_empty_file - Designates if empty files are allowed.
  • use_url - If set to True then URL string values will be used for the output representation. If set to False then filename string values will be used for the output representation. Defaults to the value of the UPLOADED_FILES_USE_URL settings key, which is True unless set otherwise.

Pillow 패키지 또는 PIL 패키지가 필요합니다. PIL이 더 이상 적극적으로 유지관리도지 않으므로 Pillow 패키지를 사용하는 것이 좋습니다.

Composite fields

ListField

개체 목록의 유효성을 검사하는 필드 클래스입니다.

Signature: ListField(child=<A_FIELD_INSTANCE>, allow_empty=True, min_length=None, max_length=None)

  • child - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated.
  • allow_empty - Designates if empty lists are allowed.
  • min_length - Validates that the list contains no fewer than this number of elements.
  • max_length - Validates that the list contains no more than this number of elements.

예를 들어, 정수 목록의 유효성을 검사하려면 다음과 같은 것을 사용할 수 있습니다.

scores = serializers.ListField(
   child=serializers.IntegerField(min_value=0, max_value=100)
)

LIstField 클래스는 재사용 가능한 목록 필드 클래스를 작성할 수 있는 선언적 스타일도 지원합니다.

class StringListField(serializers.ListField):
    child = serializers.CharField()

이제 자식 인수를 제공하지 않고도 애플리케이션 전체에서 사용자 지정 StringListField 클래스를 재사용할 수 있습니다.

DictField

개체 사전의 유효성을 검사하는 필드 클래스입니다. DictField의 키는 항상 문자열 값으로 간주됩니다.

Signature: DictField(child=<A_FIELD_INSTANCE>, allow_empty=True)

  • child - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated.
  • allow_empty - Designates if empty dictionaries are allowed.

예를 들어 문자열과 문자열의 매핑을 검증하는 필드를 생성하려면 다음과 같이 작성합니다.

document = DictField(child=CharField())

ListField와 마찬가지로 선언적 스타일을 사용할 수 있습니다.

class DocumentField(DictField):
    child = CharField()

HStoreField

Django의 postgres HStoreField와 호환되는 사전 구성된 DictField입니다.

Signature: HStoreField(child=<A_FIELD_INSTANCE>, allow_empty=True)

  • child - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values.
  • allow_empty - Designates if empty dictionaries are allowed.

hstore 익스텐션은 값을 문자열로 저장하므로 자식 필드는 CharField의 인스턴스여야 합니다.

JSONField

들어오는 데이터 구조가 유효한 JSON 프리미티브로 구성되어 있는지 확인하는 필드 클래스입니다. 대체 바이너라 모드에서는 JSON으로 인코딩된 바이너리 문자열을 나타내고 유효성을 검사합니다.

Signature: JSONField(binary, encoder)

  • binary - If set to True then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to False.
  • encoder - Use this JSON encoder to serialize input object. Defaults to None.

Miscellaneous fields

ReadOnlyField

update없이 필드 값을 단순히 반환하는 필드 클래스입니다.

이 필드는 모델 필드가 아닌 속성과 관련된 필드 이름을 포함할 때 ModelSerializer와 함께 기본적으로 사용됩니다.

Signature: ReadOnlyField()

For example, if has_expired was a property on the Account model, then the following serializer would automatically generate it as a ReadOnlyField:

class AccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = Account
        fields = ['id', 'account_name', 'has_expired']

HiddenField

사용자 입력을 기반으로 하는 값을 사용하지 않고 대신 기본값 또는 호출 가능 항목에서 값을 사용하는 필드 클래스입니다.

Signature: HiddenField()

예를 들어, 항상 현재 시간을 시리얼라이저 벨리데이터된 데이터의 일부로 제공하는 필드를 포함하려면 다음을 사용합니다.

modified = serializers.HiddenField(default=timezone.now)

HiddenField 클래스는 일반적으로 미리 제공된 일부 필드 값을 기반으로 실행해야 하는 유효성 검사가 있지만 이러한 모든 필드를 최종 사용자에게 노출하고 싶지 않은 경우에만 필요합니다.

HiddenField에 대한 벨리데이터는 다음 링크를 참고하면 되겠습니다.

https://www.django-rest-framework.org/api-guide/validators/

 

Validators - Django REST framework

 

www.django-rest-framework.org

 

ModelField

임의의 모델필드에 연결할 수 있는 일반 필드입니다. ModelField 클래스는 직렬화/역직렬화 작업을 연결된 모델 필드에 위임합니다. 이 필드는 새 사용자 정의 시리얼라이저를 만들 필요 없이 사용자 정의 모델 필드에 대한 시리얼라이저 필드를 만드는데 사용할 수 있습니다.

이 필드는 ModelSerializer에서 사용자 지정 모델 필드 클래스에 해당하는 데 사용됩니다.

Signature: ModelField(model_field=<Django ModelField instance>)

The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField, it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field'))

SerializerMethodField

이 필드는 읽기 전용 필드입니다. 연결된 시리얼라이저 클래스의 메서드를 호출하여 값을 가져옵니다. 객체의 직렬화된 표현에 모든 종류의 데이터를 추가하는 데 사용할 수 있습니다.

Signature: SerializerMethodField(method_name=None)

  • method_name - The name of the method on the serializer to be called. If not included this defaults to get_<field_name>.

method_name 아규먼트가 참조하는 시리얼라이저 메서드는 직렬화되는 개체인 단일 아규먼트(self외)를 허용해야 합니다. 객체의 직렬화된 표현에 포함하려는 모든 것을 반환해야 합니다.

from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers

class UserSerializer(serializers.ModelSerializer):
    days_since_joined = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = '__all__'

    def get_days_since_joined(self, obj):
        return (now() - obj.date_joined).days

Custom fields

사용자 정의 필드를 생성하려면 Field를 서브클래스화한 다음 .to_representation() 및 .to_internal_value() 메소드 중 하나 또는 둘 다를 재정의해야 합니다. 이 두 가지 방법은 초기 데이터 유형과 직렬화 가능한 기본 데이터 유형 사이를 반환하는 데 사용됩니다. 기본 데이터 유형은 일반적으로 숫자, 문자열, 부울, date/time/datetime 또는 None중 하나입니다. 또한 다른 기본 객체만 포함하는 객체와 같은 list나 딕셔너리일 수도 있습니다. 사용 중인 렌더러에 따라 다른 유형이 지원될 수 있습니다.

.to_representation() 메소드는 초기 데이터 유형을 직렬화 가능한 기본 데이터 유형으로 변환하기 위해 호출됩니다.

.to_internal_value() 메서드는 기본 데이터 유형을 내부 파이썬 표현으로 복원하기 위해 호출됩니다. 이 메서드는 데이터가 유효하지 않은 경우 serializers.ValidationError를 발생시켜야 합니다.

예시 코드

기본 사용자 정의 필드

RGB 색상 값을 나타내는 클래스를 직렬화 하는 예시를 살펴보겠습니다.

class Color:
    """
    A color represented in the RGB colorspace.
    """
    def __init__(self, red, green, blue):
        assert(red >= 0 and green >= 0 and blue >= 0)
        assert(red < 256 and green < 256 and blue < 256)
        self.red, self.green, self.blue = red, green, blue

class ColorField(serializers.Field):
    """
    Color objects are serialized into 'rgb(#, #, #)' notation.
    """
    def to_representation(self, value):
        return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue)

    def to_internal_value(self, data):
        data = data.strip('rgb(').rstrip(')')
        red, green, blue = [int(col) for col in data.split(',')]
        return Color(red, green, blue)

기본적으로 필드 값은 개체의 특성에 대한 매핑으로 처리됩니다. 필드 값에 액세스하고 설정하는 방법을 사용자 정의해야 하는 경우 .get_attribute() 및/또는 .get_value()를 재정의해야 합니다. 예를 들어 직렬화되는 개체의 클래스 이름을 나타내는 데 사용할 수 있는 필드를 만들어 보겠습니다.

class ClassNameField(serializers.Field):
    def get_attribute(self, instance):
        # We pass the object instance onto `to_representation`,
        # not just the field attribute.
        return instance

    def to_representation(self, value):
        """
        Serialize the value's class name.
        """
        return value.__class__.__name__

Raising validation errors

위의 ColorField 클래스는 현재 데이터 유효성 검사를 수행하지 않습니다. 유효하지 않은 데이터를 나타내려면 다음과 같이 serializers.ValidationError를 발생시켜야합니다.

def to_internal_value(self, data):
    if not isinstance(data, str):
        msg = 'Incorrect type. Expected a string, but got %s'
        raise ValidationError(msg % type(data).__name__)

    if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
        raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.')

    data = data.strip('rgb(').rstrip(')')
    red, green, blue = [int(col) for col in data.split(',')]

    if any([col > 255 or col < 0 for col in (red, green, blue)]):
        raise ValidationError('Value out of range. Must be between 0 and 255.')

    return Color(red, green, blue)

.fail() 메서드는 error_messages 사전에서 메시지 문자열을 가져오는 ValidationError를 발생시키는 지름길입니다. 예시는 다음과 같습니다.

default_error_messages = {
    'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}',
    'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.',
    'out_of_range': 'Value out of range. Must be between 0 and 255.'
}

def to_internal_value(self, data):
    if not isinstance(data, str):
        self.fail('incorrect_type', input_type=type(data).__name__)

    if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data):
        self.fail('incorrect_format')

    data = data.strip('rgb(').rstrip(')')
    red, green, blue = [int(col) for col in data.split(',')]

    if any([col > 255 or col < 0 for col in (red, green, blue)]):
        self.fail('out_of_range')

    return Color(red, green, blue)

이 스타일은 오류 메시지를 더 명확하고 코드에서 분리하여 유지하므로 선호해야합니다.

Using source='*'

여기에서는 x_coordinate 및 y_coordinate 속성이 있는 평면 DataPoint 모델의 예를 살펴보겠습니다.

class DataPoint(models.Model):
    label = models.CharField(max_length=50)
    x_coordinate = models.SmallIntegerField()
    y_coordinate = models.SmallIntegerField()

사용자 정의 필드와 source='*'를 사용하여 좌표 쌍의 중첩 표현을 제공할 수 있습니다.

class CoordinateField(serializers.Field):

    def to_representation(self, value):
        ret = {
            "x": value.x_coordinate,
            "y": value.y_coordinate
        }
        return ret

    def to_internal_value(self, data):
        ret = {
            "x_coordinate": data["x"],
            "y_coordinate": data["y"],
        }
        return ret


class DataPointSerializer(serializers.ModelSerializer):
    coordinates = CoordinateField(source='*')

    class Meta:
        model = DataPoint
        fields = ['label', 'coordinates']

이 예제에서는 유효성 검사를 처리하지 않습니다. 부분적으로 그러한 이유 때문에 실제 프로젝트에서 좌표 중첩은 각각 관련 필드를 가리키는 자체 소스가 있는 두 개의 IntegerField 인스턴스와 함께 source='*'를 사용하는 중첩 직렬 변환기로 더 잘 처리될 수 있습니다.

그러나 예제의 요점은 다음과 같습니다.

  • to_representation은 전체 DataPoint 개체에 전달되며 이 개체에서 원하는 출력으로 매핑해야 합니다.
>>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2)
>>> out_serializer = DataPointSerializer(instance)
>>> out_serializer.data
ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})])

필드가 읽기 전용이 아닌 한 to_internal_value는 대상 개체를 업데이트하는 데 적합한 사전으로 다시 매핑되어야 합니다. source='*'인 경우 to_internal_value에서 반환하면 단일 키가 아니라 루트 유효성 검사 데이터 딕셔너리가 update 됩니다.

>>> data = {
...     "label": "Second Example",
...     "coordinates": {
...         "x": 3,
...         "y": 4,
...     }
... }
>>> in_serializer = DataPointSerializer(data=data)
>>> in_serializer.is_valid()
True
>>> in_serializer.validated_data
OrderedDict([('label', 'Second Example'),
             ('y_coordinate', 4),
             ('x_coordinate', 3)])

완전성을 위해 위에서 제안한 중첩 직렬 변환기 접근 방식을 사용하여 동일한 작업을 다시 수행할 수 있습니다.

class NestedCoordinateSerializer(serializers.Serializer):
    x = serializers.IntegerField(source='x_coordinate')
    y = serializers.IntegerField(source='y_coordinate')


class DataPointSerializer(serializers.ModelSerializer):
    coordinates = NestedCoordinateSerializer(source='*')

    class Meta:
        model = DataPoint
        fields = ['label', 'coordinates']

여기에서 대상 및 소스 애트리뷰트 쌍(x 및 x_coordinate, y 및 y_coordinate)간의 매핑은 IntegerField 선언에서 처리됩니다. source='*'를 취하는 것은 NestedCoordinateSerializer입니다.

Serializing:

>>> out_serializer = DataPointSerializer(instance)
>>> out_serializer.data
ReturnDict([('label', 'testing'),
            ('coordinates', OrderedDict([('x', 1), ('y', 2)]))])

Deserializing:

>>> in_serializer = DataPointSerializer(data=data)
>>> in_serializer.is_valid()
True
>>> in_serializer.validated_data
OrderedDict([('label', 'still testing'),
             ('x_coordinate', 3),
             ('y_coordinate', 4)])

그러나 기본적으로 유효성 검사를 받을 수 있습니다.

>>> invalid_data = {
...     "label": "still testing",
...     "coordinates": {
...         "x": 'a',
...         "y": 'b',
...     }
... }
>>> invalid_serializer = DataPointSerializer(data=invalid_data)
>>> invalid_serializer.is_valid()
False
>>> invalid_serializer.errors
ReturnDict([('coordinates',
             {'x': ['A valid integer is required.'],
              'y': ['A valid integer is required.']})])

이러한 이유로 중첩 시리얼라이저 접근 방식이 가장 먼저 시도됩니다. 중첩된 시리얼라이저가 실행 불가능하거나 지나치게 복잡해지면 사용자 정의 필드 접근 방식을 사용합니다.

참고 링크 : https://www.django-rest-framework.org/api-guide/fields/#filefield

 

Serializer fields - Django REST framework

 

www.django-rest-framework.org

 

'Django > Django REST framework' 카테고리의 다른 글

12-Validators  (0) 2021.08.18
11. Serializer relations  (0) 2021.07.18
9-3 Serializer-3  (0) 2021.07.15
9-2 Serializers-2  (0) 2021.07.15
9-1. Serializers  (0) 2021.07.15

댓글