购物车数据同步(中间件):
class SessionSyncMiddleware(MiddlewareMixin):
def process_response(self, request, response):
# 没有登录就不管数据同步
# 登录情况才做数据从session同步到数据库,且重新更新session数据
user_id = request.session.get('user_id')
if user_id:
# 登录情况
session_goods = request.session.get('goods')
if session_goods:
# 1.判断session中商品是否存在于数据库中,如果存在,则更新
# 2.如果不存在则创建
shop_carts = ShoppingCart.objects.filter(user_id=user_id)
# 更新购物车中的商品数量
data = []
for goods in shop_carts:
for se_goods in session_goods:
if se_goods[0] == goods.goods_id:
goods.nums = se_goods[1]
goods.save()
# 向data中添加编辑了的商品的id值
data.append(se_goods[0])
# 添加
session_goods_ids = [i[0] for i in session_goods]
add_goods_ids = list(set(session_goods_ids) - set(data))
for add_goods_id in add_goods_ids:
for session_good in session_goods:
if add_goods_id == session_good[0]:
ShoppingCart.objects.create(user_id=user_id, goods_id=add_goods_id, nums=session_good[1])
# 将数据库中数据同步到session中
new_shop_carts = ShoppingCart.objects.filter(user_id=user_id)
session_new_goods = [[i.goods_id, i.nums, i.is_select] for i in new_shop_carts]
request.session['goods'] = session_new_goods
return response
购物车数据删除:
def del_cart(request, id):
if request.method == 'GET':
user_id = request.session.get('user_id')
if user_id:
# 登录情况,删除数据库中的数据
ShoppingCart.objects.filter(user_id=user_id, goods_id=id).delete()
# 没有登录情况,删除session中的数据
session_goods = request.session.get('goods')
for goods in session_goods:
if goods[0] == int(id):
session_goods.remove(goods)
request.session['goods'] = session_goods
return HttpResponseRedirect(reverse('carts:cart'))
同步数据库商品数目:
def change_cart(request):
if request.method == 'POST':
# 获取前端ajax传递的goods_id,is_select,nums
goods_id = int(request.POST.get('goods_id'))
is_select = request.POST.get('is_select')
nums = request.POST.get('nums')
# 获取session中商品的信息
session_goods = request.session.get('goods')
for goods in session_goods:
# goods:[goods_id, nums, is_select]
if goods_id == goods[0]:
# 修改session中的商品的数量和选择状态
goods[1] = int(nums) if nums else goods[1]
goods[2] = is_select if nums else goods[2]
request.session['goods'] = session_goods
return JsonResponse({'code': 200, 'msg': '请求成功'})
网友评论