Kamusta,我是Charlie!
在Day14中,我們完成了前端的購物車商品顯示跟加入購物車,而今天,我們將完成購物車數量增減跟刪除的後端API。
================================◉‿◉=================================
首先是加減購物車,因為我們是spinButton,所以會用v-model的值來判斷,我們的API就是依照數量來做加減。
先新增PUT方法,去修改相對應的購物車數量。
一樣要新增判斷,判斷amount為0、product找不到、user找不到都會返回對應的訊息,如果都OK的話就指定amount回去,然後save:
elif request.method == "PUT":
req = request.body
ucart = CartModel()
ucart.fromJson(req)
if ucart.amount == 0:
return R.badRequest("Cart amount can not be 0")
product = Product.objects.filter(id = ucart.product_id)
if not product:
return R.badRequest("Product does not exist!")
product = product[0]
if ucart.amount > product.stored_amount:
return R.badRequest("Add cart amount reach maximum stored amount")
user = User.objects.filter(name = ucart.username)
if not user:
return R.badRequest("User does not exist!")
user = user[0]
dbcart = Cart.objects.filter(user = user).filter(product = product)
dbcart = dbcart[0]
dbcart.amount = ucart.amount
dbcart.save()
return R.ok("amount change success")
接著測試:
再來是DELETE的部分,一樣新增DELETE方法:
elif request.method == "DELETE":
由於DELETE方法不應該帶任何的request body,所以我們需要用url帶參數,首先修改url pattern:
url(r'/(?P<cid>[\d]{1,55})$',views.usercart),
並且增加cid參數,再判斷delete,執行相對應的方法:
def usercart(request,username = None,cid = None):
elif request.method == "DELETE" and cid is not None:
cid = int(cid)
cart = Cart.objects.filter(id = cid)
if not cart:
return R.badRequest("Cart record does not exist")
cart = cart[0]
cart.delete()
return R.ok("delete success")
測試:
================================◉‿◉=================================
Day15結束了!在今天我們完成了後端的購物車數量改變跟刪除,而明天我們將完成前端的購物車數量改變跟刪除,See ya next day!