Expanding the usefulness of the serializers is something that we would like to address. However, it's not a trivial problem, and it will take some serious design work.
— Russell Keith-Magee, Django users group
출처 : https://www.django-rest-framework.org/api-guide/serializers/
serialize란 한글로 해석하면 직렬화이다. python 에서 존재하는 model이나 queryset 등 복잡한 형태를 JSON, XML 등과 같은 쉬운 데이터로 변환시켜 주는 것이다. DRF 에서는 주로 JSON을 통해 프론트엔드와 통신을 하기 때문에 Serializer는 매우 필수적인 객체이다.
1. GET method를 통해 객체를 JSON으로 줄 때
2. POST method를 통해 request body에 담긴 JSON data를 역직렬화하여 저장할 때
이렇게 대표적인 예시가 있다.
역직렬화는 deserialize라고 하지만, DRF에서는 serializer가 이 역할도 해준다. (즉, deserializer가 따로 있지는 않다)
기본적으로 Serializer가 있지만 이는 모델의 field를 하나하나 직접 구현해야 한다.
그래서 Model을 이용해 쉽게 만들 수 있는 ModelSerializer가 있다. 이 포스트에서는 이를 사용할 것이다.
ModelSerializer는 해당하는 모델에 대해 자동으로 생성해주는 Serializer이다.
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ['id', 'account_name', 'users', 'created']
이러한 식으로 model, fields를 지정할 수 있다.
모든 필드를 사용한다면
fields = '__all__로 지정하면 된다.
exclude 로 예외설정 가능
depth 를 이용하면 foreign_key로 연결된 model 의 정보도 가져올 수 있다.
class Book(models.Model):
author = models.ForeignKey("Author", on_delete=models.CASCADE)
context = models.TextField(blank=True)
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '['id', 'context', 'author']'
해당 예시에서 book에서 author가 Foreignkey 로 연결이 되어 있을 때, 단순히 호출하면

다음과 같이 author의 id 가 나온다.
하지만
class BookSerializer(serializers.ModelSerializer):
# author = AuthorSerializer() // 수동으로 생성하는 법
class Meta:
model = Book
fields = '['id', 'context', 'author']'
depth = 1
해당 코드처럼 depth를 추가하면

author Model까지 출력시키는 것을 확인할 수 있다.
DJ앙고에 대해 아시나요?