Advertisement
denees_k

Untitled

Jul 2nd, 2025 (edited)
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. def create_order(request):
  2.     if request.method != 'POST':
  3.         return HttpResponseNotAllowed(['POST'])
  4.  
  5.     product_id = request.POST.get('product_id')
  6.     if not product_id:
  7.         return HttpResponseBadRequest("Missing product_id")
  8.  
  9.     try:
  10.         with transaction.atomic():
  11.             product = ProductStock.objects.select_for_update().get(id=product_id)
  12.  
  13.             if product.count <= 0:
  14.                 return JsonResponse({"status": "error", "message": "Out of stock"}, status=400)
  15.  
  16.             product.count -= 1
  17.             product.save()
  18.  
  19.             # Создаем заказ
  20.             order = Order.create(product=product)
  21.  
  22.         return JsonResponse({"status": "success", "order_id": order.id})
  23.  
  24.     except DoesNotExist:
  25.         return JsonResponse({"status": "error", "message": "Product not found"}, status=404)
  26.     except Exception as e:
  27.         return JsonResponse({"status": "error", "message": str(e)}, status=500)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement