Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def create_order(request):
- if request.method != 'POST':
- return HttpResponseNotAllowed(['POST'])
- product_id = request.POST.get('product_id')
- if not product_id:
- return HttpResponseBadRequest("Missing product_id")
- try:
- with transaction.atomic():
- product = ProductStock.objects.select_for_update().get(id=product_id)
- if product.count <= 0:
- return JsonResponse({"status": "error", "message": "Out of stock"}, status=400)
- product.count -= 1
- product.save()
- # Создаем заказ
- order = Order.create(product=product)
- return JsonResponse({"status": "success", "order_id": order.id})
- except DoesNotExist:
- return JsonResponse({"status": "error", "message": "Product not found"}, status=404)
- except Exception as e:
- return JsonResponse({"status": "error", "message": str(e)}, status=500)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement