python 54 lines · 9 steps

Placing an order atomically in Django

A transactional order flow that locks stock rows, validates a cart, and commits inventory and line items together.

Explained by highlit
1from decimal import Decimal
2 
3from django.db import transaction
4from django.core.exceptions import ValidationError
5 
6from .models import Product, Order, OrderItem
7 
8 
9@transaction.atomic
10def place_order(customer, cart_items):
11 product_ids = [item["product_id"] for item in cart_items]
12 
13 products = (
14 Product.objects
15 .select_for_update()
16 .filter(id__in=product_ids, is_active=True)
17 .in_bulk()
18 )
19 
20 order = Order.objects.create(customer=customer, status=Order.Status.PENDING)
21 line_items = []
22 total = Decimal("0.00")
23 
24 for item in cart_items:
25 quantity = item["quantity"]
26 product = products.get(item["product_id"])
27 
28 if product is None:
29 raise ValidationError(f"Product {item['product_id']} is unavailable.")
30 if product.stock < quantity:
31 raise ValidationError(
32 f"Only {product.stock} left of {product.name}."
33 )
34 
35 product.stock -= quantity
36 line_items.append(
37 OrderItem(
38 order=order,
39 product=product,
40 quantity=quantity,
41 unit_price=product.price,
42 )
43 )
44 total += product.price * quantity
45 
46 Product.objects.bulk_update(products.values(), ["stock"])
47 OrderItem.objects.bulk_create(line_items)
48 
49 order.total = total
50 order.status = Order.Status.CONFIRMED
51 order.save(update_fields=["total", "status"])
52 
53 transaction.on_commit(lambda: order.send_confirmation_email())
54 return order
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping the whole flow in a transaction means any validation failure rolls back every write, so orders never partially commit.
  2. 2select_for_update locks the product rows for the transaction's duration, preventing two concurrent checkouts from overselling the same stock.
  3. 3Side effects like emails belong in on_commit so they only fire once the data is durably saved.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Placing an order atomically in Django — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code