经过几轮的视图类的编写,整个电商项目的逻辑有清晰一点了么?对于事务逻辑的数据处理,分为查询和创建。相对于本项目来说,创建的操作大多数在用户下单到支付成功这一过程,所以在提交订单的类中,用到了数据库事务,对数据的一致性处理提供了保障。
① 提供评论页面
查询到支付成功的订单,通过反向查询找到所有商品。
def get(self, request, order_id):
"""提供评论页面"""
user = request.user
try:
order = OrderInfo.objects.get(order_id=order_id, user=user)
except OrderInfo.DoesNotExist:
return redirect(reverse("orders:info"))
order.status_name = OrderInfo.ORDER_STATUS[order.status]
order.skus = []
order_skus = order.ordergoods_set.all()
for order_sku in order_skus:
sku = order_sku.sku
sku.count = order_sku.count
sku.amount = sku.price * sku.count
order.skus.append(sku)
return render(request, "order_comment.html", {"order": order})
② 处理评论内容
def post(self, request, order_id):
"""处理评论内容"""
user = request.user
try:
order = OrderInfo.objects.get(order_id=order_id, user=user)
except OrderInfo.DoesNotExist:
return redirect(reverse("orders:info"))
# 获取评论条数
total_count = request.POST.get("total_count")
total_count = int(total_count)
for i in range(1, total_count + 1):
sku_id = request.POST.get("sku_%d" % i)
content = request.POST.get('content_%d' % i, '')
try:
order_goods = OrderGoods.objects.get(order=order, sku_id=sku_id)
except OrderGoods.DoesNotExist:
continue
order_goods.comment = content
order_goods.save()
# 清除商品详情缓存
cache.delete("detail_%s" % sku_id)
order.status = OrderInfo.ORDER_STATUS_ENUM["FINISHED"]
order.save()
return redirect(reverse("orders:info", kwargs={"page": 1}))
③ 订单评论类视图
class CommentView(LoginRequiredMixin, View):
"""订单评论"""
def get(self, request, order_id):
"""提供评论页面"""
user = request.user
try:
order = OrderInfo.objects.get(order_id=order_id, user=user)
except OrderInfo.DoesNotExist:
return redirect(reverse("orders:info"))
order.status_name = OrderInfo.ORDER_STATUS[order.status]
order.skus = []
order_skus = order.ordergoods_set.all()
for order_sku in order_skus:
sku = order_sku.sku
sku.count = order_sku.count
sku.amount = sku.price * sku.count
order.skus.append(sku)
return render(request, "order_comment.html", {"order": order})
def post(self, request, order_id):
"""处理评论内容"""
user = request.user
try:
order = OrderInfo.objects.get(order_id=order_id, user=user)
except OrderInfo.DoesNotExist:
return redirect(reverse("orders:info"))
# 获取评论条数
total_count = request.POST.get("total_count")
total_count = int(total_count)
for i in range(1, total_count + 1):
sku_id = request.POST.get("sku_%d" % i)
content = request.POST.get('content_%d' % i, '')
try:
order_goods = OrderGoods.objects.get(order=order, sku_id=sku_id)
except OrderGoods.DoesNotExist:
continue
order_goods.comment = content
order_goods.save()
# 清除商品详情缓存
cache.delete("detail_%s" % sku_id)
order.status = OrderInfo.ORDER_STATUS_ENUM["FINISHED"]
order.save()
return redirect(reverse("orders:info", kwargs={"page": 1}))