- data를 serialization하여 JSON으로 변환하는 방법 학습
[N:1 참조 조회]
[실습 사전 준비]
파일 경로 ➡️ articles/models.py

$ python manage.py makemigrations
$ python manage.py migrate
- Comment 모델 작성 및 데이터베이스 초기화 & migration
GET - LIST
파일 경로 ➡️ articles/serializers.py

파일 경로 ➡️ articles/urls.py

파일 경로 ➡️ articles/views.py

GET = DETAIL
- 단일 댓글 데이터 조회하기
- Article과 달리 같은 serializer 사용하기
파일 경로 ➡️ articles/urls.py

파일 경로 ➡️ articles/views.py

POST
파일 경로 ➡️ articles/urls.py

파일 경로 ➡️ articles/views.py

- line 6
- save() 메서드는 특정 Serializer 인스턴스를 저장하는 과정에서 추가적인 데이터를 받을 수 있음
- CommentSerializer를 통해 Serialize 되는 과정에서 parameter로 넘어온 article_pk에 해당하는 article 객체를 추가적인 데이터를 넘겨 저장
파일 경로 ➡️ articles/serializers.py

- CommentSerializer에서 article field 데이터 또한 사용자로부터 입력받도록 설정되어있어 에러가 발생
- read_only_fields를 사용해 외래 키 필드를 읽기전용 필드로 설정
- 읽기전용 필드는 데이터를 전송하는 시점에 '해당필드를 유효성 검사에서 제외시키고 데이터 조회시에는 출력' 하도록 함
DELETE & PUT
파일 경로 ➡️ articles/views.py

[N:1 역참조 데이터 조회]
- 특정 게시글에 작성된 댓글 목록 출력하기
- 특정 게시글에 작성된 댓글의 개수 출력하기
[특정 게시글에 작성된 댓글 목록 출력하기]
- 기존 필드 override - Article Detail
- 게시글 조회 시 해당 게시글의 댓글 목록까지 함께 출력하기
- Serializer는 기존 필드를 override 하거나 추가적인 필드를 구성할 수 있음
파일 경로 ➡️ articles/serializers.py


- models.py에서 related_name을 이용하여 이름 변경 가능
- 역참조 시 생성되는 comment_set을 override 할 수 있음
2. Nested relationships
- 모델 관계 상으로 참조 된 대상은 참조하는 대상의 표현에 포함되거나 중첩될 수 있음
- 이러한 중첩된 관계는 serializers를 필드로 사용하여 표현할 수 있음
- 두 클래스의 상/하 위치를 변경해야함
파일 경로 ➡️ articles/serializers.py

[특정 게시글에 작성된 댓글의 개수 출력하기]
- 새로운 필드 추가 - Article Detail
- 게시글 조회 시 해당 게시글 댓글 개수까지 함게 출력하기
파일 경로 ➡️ articles/serializers.py

- line 3 : source
- serializes field's argument
- 필드를 채우는 데 사용할 속성의 이름
- 점 표기법을 사용하여 속성을 탐색할 수 있음
[Django shortcuts function]
- django.shortcut 패키지는 개발에 도움 될 수 있는 여러 함수와 클래스를 제공
- 제공되는 shortcuts 목록
- render(), redirect(), get_object_or_404(), get_list_or_404()
1. get_object_or_404()

- 모델 manager objects에서 get()을 호출하지만, 해당 객체가 없을 땐 기존 DoesNotExist 예외 대신 Http404를 raise함
2. get_list_or_404()

- 모델 manager objects에서 filter() 결과를 반환하고 해당 객체 목록이 없을 땐 Http404를 raise함
왜 사용해야 할까?
- 클라이언트 입장에서 "서버에 오류가 발생하여 요청을 수행할 수 없다(500)"라는 원인이 정확하지 않은 에러를 마주하기 보다는, 서버가 적절한 예외처리를 하고 클라이언트에게 올바른 에러를 전달하는 것 또한 중요한 요소이기 때문