# https://www.cnblogs.com/yloven/p/6964936.html
from django.db import transaction
#首先要导包
@transaction.atomic
@innerdef list(request):
post= request.POST
address = post.get('email')
cart_id=post.getlist('cart_id')
# 在调用一个view里面的方法之前,django开始一个事务如果发出的响应没有问题,
# Django就会提交这个事务。如果在view这里产生一个异常,Django就会回滚这次事务
# 开启事物保护
sid = transaction.savepoint()
try:
# 1.建立新的订单信息
# transaction.savepoint_commit(sid) #事物的提交
order = OrderInfo()
now = datetime.now()
uid = request.session['user_id']
order.oid=('%s%d')%(now.strftime('%Y%m%d%H%M%S'), uid) # 拼接字符代码
order.user_id=uid
order.udate = now
order.oaddress = address
print(order.oaddress,order.udate,order.user_id,order.oid,uid,now)
order.otatal=0
order.save()
total=0 # 计算好的总价
for cid in cart_id:
cart=CartInfo.objects.get(pk=cid)
# 2.判断库存,减少数据库库存
if cart.goods.gkucun>=cart.count:
cart.goods.gkucun-=cart.count
cart.goods.save() # 连表保存数据库的值
# 把信息添加订单
datail = OrderDetailInfo()
datail.order=order # 保存的外键对应ID
datail.goods=cart.goods #保存外键对应Id
datail.price=cart.goods.gprice
datail.count=cart.count
# print(order,cart.goods,cart.goods.gprice)
datail.save()
# 计算总价
total+=cart.goods.gprice*cart.count
# 购车用完了删除
cart.delete()
else: # 购车数量比库存大
transaction.savepoint_rollback(sid) #事务的回滚
return redirect('/cart/')
order.ototal = total
print(total)
order.save() # 计算完了 保存总价格
transaction.savepoint_commit(sid) #提交事务的逻辑
return redirect('/user/order/1')
except :
# 发生异常就回滚
transaction.savepoint_rollback(sid)