장바구니 리스트 구현

Junyoung Lee·2021년 7월 11일
0

1stProject

목록 보기
1/3

프로젝트를 진행하며 장바구니 목록을 구현하며 적어보려고 합니다!


만들어 본 Cart list View

GET 메서드로 유저가 가지고 있는 장바구니의 제품 목록을 가져와 봤다!

CartView 코드✍🏻

class CartView(View):
    @login_decorator
    def get(self, request):
        try:
            signed_user = request.user
            items       = CartItem.objects.filter(user=signed_user)
            cart_lists  = [
                    {
                    'cartItemId': item.id,
                    'thumbnail' : item.product_options.product.thumbnail,
                    'name'      : item.product_options.product.name,
                    'option'    : item.product_options.option.name,
                    'price'     : item.product_options.product.price,
                    'grams'     : item.product_options.product.grams,
                    'quantity'  : item.quantity
                    } for item in items
            ]
            return JsonResponse({'cartItems':cart_lists}, status=200)

        except KeyError:
            return JsonResponse({'message':'KEY_ERROR'}, status=400)

        except User.DoesNotExist:
            return JsonResponse({'message':'INVALID_USER'}, status=400)

구현 내용

  • 데코레이터를 사용해 유저정보 가져옴
  • 현재 유저의 장바구니에 있는 제품들을 return

장바구니 리스트 프로세스

  1. 데코레이터를 사용하여 유저의 정보 유효성 검사
  2. 변수에 request의 user에 담긴 유효한 유저를 넣음
  3. 유저가 가지고 있는 장바구니 제품들을 쿼리셋으로 가져옴
  4. 리스트 컴프리헨션으로 제품의 정보들을 리스트에 담음
  5. 리스트를 return

나도 끝!

profile
🎹재즈를 사랑하는 백엔드 개발자 이준영입니다🎷

0개의 댓글