2022.04.02 til

장바구니의 나머지 기능인 보기, 수량변경, 삭제를 구현했다.
보기

    @logindeco
    def get(self, request):
        user = request.user
        carts = Cart.objects.filter(user = user)

        if not Cart.objects.filter(user=user).exists():
            return JsonResponse({'message' : 'INVALID_USER'}, status = 400)
        
        result = [{
            'user_id'   : user.id,
            'cart_id'   : cart.id,
            'quantity'  : cart.quantity,
            'product_id': cart.product.id
            }for cart in carts]

        return JsonResponse({'message' : result}, status = 200)

수량변경

    @logindeco
    def patch(self, request):
        try:
            data       = json.loads(request.body)
            user       = request.user
            product_id = data['product_id']
            quantity   = data['quantity']
            product    = Product.objects.get(id = product_id)

            if quantity <= 0 or quantity >= 5:
                    return JsonResponse({'message' : 'INVALID_QUANTITY'}, status = 400)

            if not Product.objects.filter(id = product_id).exists():
                    return JsonResponse({'message' : 'INVALID_PRODUCT_ID'}, status = 400)

            if Cart.objects.filter(product_id = product).exists():
                    cart          = Cart.objects.get(user = user, product_id = product)
                    cart.quantity = quantity
                    cart.save()
                    return JsonResponse({'message' : 'QUANTITY_CHANGED'}, status = 201)
            return JsonResponse({'message' : 'NO_PRODUCT_IN_CART'}, status = 400)
            
        except KeyError:
            return JsonResponse({'message' : 'KEY_ERROR'}, status = 400)

삭제

    @logindeco
    def delete(self, request):
        try:
            data       = json.loads(request.body)
            user       = request.user
            product_id = data['product_id']
            cart_check = Cart.objects.filter(user_id = user, product_id = product_id)

            if not cart_check .exists():
                return JsonResponse({'message' : 'CART_DOES_NOT_EXIST'}, status = 400)
            cart_check .delete()

            return JsonResponse({'message' : 'PRODUCT_DELETED'}, status = 200)

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

좋은 웹페이지 즐겨찾기