购物车商品修改
添加视图方法
编辑子应用 carts 目录下的 views.py 文件,在 CartView() 视图类下添加商品修改方法代码,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
...
class CartView(APIView):
...
def put(self, request): data = request.data ser = CartSerializers(data=data) ser.is_valid(raise_exception=True) sku_id = ser.validated_data['sku_id'] count = ser.validated_data['count'] selected = ser.validated_data['selected']
user = request.user if user and user.is_authenticated: redis_conn = get_redis_connection("carts") pl = redis_conn.pipeline() pl.hset('cart_%d' % user.id, sku_id, count)
if selected: pl.sadd('selected_%d' % user.id, sku_id) else: pl.srem('selected_%d' % user.id, sku_id)
pl.execute() return Response(ser.data)
|
购物车商品删除
获取要删除的数据 – 校验数据是否存在 – 执行删除 – 返回删除状态码
添加视图方法
编辑子应用 carts 目录下的 views.py 文件,在 CartView() 视图类下添加商品修改方法代码,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
...
class CartView(APIView):
...
def delete(self, request): data = request.data
sku_id = data.get('sku_id')
user = request.user if user and user.is_authenticated: redis_conn = get_redis_connection("carts") pl = redis_conn.pipeline()
pl.hdel('cart_%d' % user.id, sku_id) pl.srem('selected_%d' % user.id, sku_id)
pl.execute()
return Response(status=status.HTTP_206_PARTIAL_CONTENT)
|
购物车商品全选
添加视图方法
编辑子应用 carts 目录下的 views.py 文件,在该文件的最后添加商品全选类代码,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
...
from .serializers import CartSerializers, SKUCartSerializers,CartSelectAllSerializers
...
class CartSelectedAllView(APIView): """全选:""" def put(self, request): ser = CartSelectAllSerializers(data=request.data) ser.is_valid(raise_exception=True) selected = ser.validated_data['selected'] redis_conn = get_redis_connection("carts")
user = request.user
cart_redis_dict = redis_conn.hgetall('cart_%d' % user.id)
sku_id = cart_redis_dict.keys()
if selected: redis_conn.sadd('selected_%d' % user.id, *sku_id) else: redis_conn.srem('selected_%d' % user.id, *sku_id)
return Response(ser.data ,status=status.HTTP_204_NO_CONTENT)
|
添加商品全选路由
编辑子应用 carts 目录下的 urls.py 文件,在 urlpatterns = [ … ] 中添加商品全选访问路由,如下:
1 2 3 4 5 6 7 8 9
|
from . import views from django.urls import path, re_path
urlpatterns = [ path('carts/', views.CartView.as_view()), path('carts/selection/', views.CartSelectedAllView.as_view()), ]
|