Ssul's Blog

Django REST Framework 구조이해 본문

dev/까먹지마

Django REST Framework 구조이해

Ssul 2022. 10. 6. 00:31

| 상속 구조

 

  • View를 상속받아 APIView
  • APIView를 상속받아 GenericAPIView(*Generic 테이블처리(get queryset, get object))

  • GenericAPIView + CreateModelMixin = CreateAPIView(C, POST)
  • GenericAPIView + DestoryModelMixin = DestoryAPIView(D, DELETE)
  • GenericAPIView + ListModelMixin = ListAPIView(R, GET)
  • GenericAPIView + RetrieveModelMixin = RetrieveAPIView(R, GET)
  • GenericAPIView + UpdateModelMixin = UpdateAPIView(U, PUT(전체-필수필드체크)/PATCH(일부-필수필드미체크))
    • PUT: 모델에서 필수인 내용중, serializer에서 사용하는 필드만 체크

  • ModelViewSet = CreateAPIView + DestoryAPIView + ListAPIView + RetrieveAPIView + UpdateAPIView

 

| 직렬화

  • Form은 html의 form, Model은 DB table 다룹니다
  • Serializer = Serialization + validation
DRF의 Serializer는 직렬화/역직렬화 모두 사용

메모리 - (직렬화) - 외부(DB, 파일, 네트워크) => GET/READ
(*instance -> dict -> bytes)
- DB에서 데이터(복수,단수) 가져오기 : qs = Post.objects.first()
- 직렬화: sr = PostSerializer(instance=qs)
- 외부에서 사용: sr.data(직렬화 결과는 .data에 있음)
{'id':1, 'title': '제목', 'contents': '본문입니다'}
- JSON형태로 추가 변환하여 Response : JSONRenderer().render(sr.data) = return Response(sr.data)

외부 - (역직렬화) - 메모리 => POST,UPDATE,DELETE,PATCH/WRITE
(*bytes -> dict -> is_valid() -> instance)
- 클라이언트에서 JSON 데이터 가져와서 dict로 변환: clientdict = JSONParser().parse(BytesIO(clientdata))
- 역직렬화: dsr = PostSerializer(data = clientdict)
- 유효성 검사: dsr.is_valid()
- 유효성 검사에 통과하면 dsr.validated_data생성, 통과못하면 dsr.errors생성
PostDict([~~~~~~~])
- Post 인스턴스 생성: instance = Post(**dsr.validated_data)
- Post 인스턴스 저장: instance.save()