내일배움캠프/내일배움캠프 TIL

내일배움캠프 TIL 71일차 - 코드 추가 개선

sogummi 2023. 6. 19. 22:45

오늘 한 것은 아니나. . . 기록해둬야 할 것 같아서

https://sogummi.tistory.com/159

 

내일배움캠프 TIL 68일차 - 코드 개선하기 (리액트, url통일의 중요성)

Today I Learned 변경 전 useEffect(() => { const fetchProductList = async () => { try { if (categoryId) { // categoryId 값이 존재할 때에만 API 요청 보내도록 수정 const response = await axios.get(`http://localhost:8000/shop/products/list/$

sogummi.tistory.com

이 날 적었던 부분 추가 개선

class ProductListViewAPI(APIView):
    '''
    작성자:장소은
    내용: 전체 상품 목록 쿼리 매개변수 통해 조건별 정렬 조회 API
    작성일: 2023.06.16
    '''
    pagination_class = CustomPagination

    def get(self, request):
        sort_by = request.GET.get('sort_by')
        if sort_by == 'hits':
            products = ShopProduct.objects.all().order_by('-hits')
        elif sort_by == 'latest':
            products = ShopProduct.objects.all().order_by('-product_date')
        elif sort_by == 'high_price':
            products = ShopProduct.objects.all().order_by('-product_price')
        elif sort_by == 'low_price':
            products = ShopProduct.objects.all().order_by('product_price')
        paginator = self.pagination_class()
        result_page = paginator.paginate_queryset(products, request)
        serializer = ProductListSerializer(result_page, many=True)

        return paginator.get_paginated_response(serializer.data)

백엔드에서 페이지네이션 처리 + 쿼리 매개변수 별 정렬 

그럼 프론트에서도 이 조건에 해당하는 처리만 해주면 간단하게 

전체상품의 쿼리 매개변수 별 정렬, 카테고리 별 정렬, 페이지네이션 까지 가능!