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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Wrapping the whole flow in a transaction means any validation failure rolls back every write, so orders never partially commit.
- 2select_for_update locks the product rows for the transaction's duration, preventing two concurrent checkouts from overselling the same stock.
- 3Side effects like emails belong in on_commit so they only fire once the data is durably saved.
Related explainers
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
php
<?php namespace App\Http\Controllers;
Streaming a filtered CSV export in Laravel
streaming
csv-export
query-builder
Intermediate
9 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
typescript
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http'; import { BehaviorSubject, Observable, throwError } from 'rxjs'; import { catchError, filter, take, switchMap } from 'rxjs/operators';
Refreshing auth tokens in an Angular interceptor
http-interceptor
token-refresh
rxjs
Advanced
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/placing-an-order-atomically-in-django-explained-python-74dc/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.