- Django Rest Framework
[serializers | 시리얼라이즈]
시리얼라이저란? REST API를 제공하는 장고 애플리케이션은 JSON 데이터를 주고받을 수 있어야 한다.
이를 위해서는 DB 인스턴스를 JSON 데이터로 변환하거나, 반대로 JSON 데이터를 DB 인스턴스로 변환할 수 있어야 한다.
이러한 목적으로 DRF에서 제공하는 클래스가 바로 시리얼라이저라고 보면된다.
→ 쉽게 말하자면, python 데이터를 JSON 타입의 데이터로 변환한다고 보면 됨
- 시리얼라이즈의 메서드
- create(): 시리얼라이저를 대상으로 save() 메소드를 호출하여 DB 인스턴스를 생성할 때의 동작 정의
- update(): 시리얼라이저를 대상으로 save() 메소드를 호출하여 DB 인스턴스를 수정하고자 할 때의 동작 정의
👉 시리얼라이저에선, create(), update() 메소드가 기본으로 제공됨으로, 세부 구현이 필요하지 않다면 정의할 필요가 없음
- Serializer fields
- 시리얼라이저는 응답으로 보낼 데이터의 형태를 정해주는 하나의 틀과 같다
- (models.py)모델을 정의한 뒤 내가 get/post/put/delete 등의 메서드를 사용할때, 각기 다르게 커스텀 된 데이터를 보내고 싶을땐 모델전체에서 내가 필요한 object만 가져와 쓸 수 있다.
- 다만, 단순히 갖다 쓰는것 뿐만 아니라 다양한 serializers 관련 함수들을 가져와 이용할 수 있다. = Serializer fields
- ImageField
이미지 표현. 업로드된 파일 내용을 알려진 이미지 형식과 일치하는 것으로 확인합니다.
django.forms.fields.ImageField 해당합니다.
서명: ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)
* max_length- 파일 이름의 최대 길이를 지정합니다.
* allow_empty_file- 빈 파일이 허용되는지 지정합니다.
* 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.
Requires either the Pillow package or PIL package. The Pillow package is recommended, as PIL is no longer actively maintained.
- SerializerMethodField
시리얼라이저MethodField
이것은 읽기 전용 필드입니다. 연결된 serializer 클래스에서 메서드를 호출하여 값을 가져옵니다. 객체의 직렬화된 표현에 모든 종류의 데이터를 추가하는 데 사용할 수 있습니다.
서명:SerializerMethodField(method_name=None)
* method_name- 호출할 serializer의 메서드 이름. 포함되지 않으면 기본값은 get_<field_name>입니다.
The serializer method referred to by the method_name argument should accept a single argument (in addition to self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:
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
👉 등.. 다양한 fields들이 있다. 꼭 참고자료 읽어보기!!!!!!!!!!!!!!!!!!!
[참고자료]
https://www.django-rest-framework.org/api-guide/serializers/
'woncoding > TIL' 카테고리의 다른 글
| TIL | 11.8.화 [Django : DRF] (0) | 2022.11.09 |
|---|---|
| TIL | 11.7.월 [Django : DRF] (0) | 2022.11.09 |
| TIL | 11.3.목 [Django : DRF] (1) | 2022.11.04 |
| TIL | 11.2.수 [AWS] (0) | 2022.11.04 |
| TIL | 11.1.화 [AWS] (0) | 2022.11.03 |