on
Refactoring 일지 1. APIView To ModelViewSet
Refactoring 일지 1. APIView To ModelViewSet
class TopicViewSet(CtrlfAuthenticationMixin, ModelViewSet): queryset = Topic.objects.all() serializer_class = TopicSerializer lookup_url_kwarg = "topic_id" @swagger_auto_schema(**SWAGGER_TOPIC_LIST_VIEW) def list(self, request, *args, **kwargs): note_id = list(kwargs.values())[0] note = Note.objects.filter(id=note_id).first() if note is None: return Response( data={"message": ERR_NOT_FOUND_MSG_MAP.get("note", ERR_UNEXPECTED)}, status=status.HTTP_404_NOT_FOUND, ) return super().list(request, *args, **kwargs) @swagger_auto_schema(**SWAGGER_TOPIC_CREATE_VIEW) def create(self, request, *args, **kwargs): ctrlf_user = self._ctrlf_authentication(request) topic_data, issue_data = self.build_data(request, ctrlf_user) topic_serializer = TopicSerializer(data=topic_data) issue_serializer = IssueCreateSerializer(data=issue_data) if topic_serializer.is_valid() and issue_serializer.is_valid(): issue_serializer.save(related_model=topic_serializer.save()) else: return Response(status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_201_CREATED) @swagger_auto_schema(**SWAGGER_TOPIC_DETAIL_VIEW) def retrieve(self, request, *args, **kwargs): return super().retrieve(self, request, *args, **kwargs) def build_data(self, request, ctrlf_user): topic_data = {"title": request.data["title"], "owners": [ctrlf_user.id], "note": request.data["note_id"]} issue_data = { "owner": ctrlf_user.id, "title": request.data["title"], "reason": request.data["reason"], "status": CtrlfIssueStatus.REQUESTED, "related_model_type": CtrlfContentType.TOPIC, "action": CtrlfActionType.CREATE, } return topic_data, issue_data
NoteViewSet과 매유 유사하다.
list() 메서드에서 Note의 경우는 url이 {BASE_URL}/notes/ 이고, cursor based pagination이다. Topic의 경우는 url이 {BASE_URL}/{note_id}/topics/ 이고, pagination이 따로 없다. paging 스펙이 따로 없었기 때문에, default값이다. default는 LimitOffsetPagination이다. ( 공식문서 )
create() 메서드를 보면, NoteViewSet의 create() 메서드와 매우 유사하다. 중복된 코드라서 리팩토링이 필요할 것 같다.
from http://jino-dev-diary.tistory.com/39 by ccl(A) rewrite - 2021-12-09 16:01:13