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)
Author And Source
이 문제에 관하여(2022.04.02 til), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@vkdtksdl789/2022.04.02-til저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)