Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 77 ยท Projects

Project: Bookstore with Cart

Build a Django bookstore: catalog models, a session-based shopping cart, checkout in a transaction that protects stock, aggregation reports and tests.

Online shops look complicated, but the core is a handful of ideas that you already know: a catalog of products, a cart that remembers what a visitor wants, and a checkout that turns the cart into a permanent order. The interesting part is doing the checkout correctly. If two people buy the last copy of a book, only one may succeed. If the payment step fails halfway, nothing may be half-saved.

In this project you will build the backend of a small bookstore with these pieces:

  • Catalog: Author and Book models with a price and stock.
  • Cart: stored in the visitor's session, so it works without an account.
  • Checkout: one database transaction that checks stock, creates the order and its items, and rolls everything back if anything fails.
  • Reports: revenue per book and per author with aggregation.
  • Tests for the rules that cost real money when they break.
erDiagram
    AUTHOR ||--o{ BOOK : writes
    ORDER ||--|{ ORDERITEM : contains
    BOOK ||--o{ ORDERITEM : "sold as"
    BOOK {
        string title
        int price_cents
        int stock
    }
    ORDERITEM {
        int quantity
        int unit_price_cents
    }

An order item remembers the price at the time of sale, so later price changes do not rewrite history.

Design rules worth knowing first

Store money as integers. Prices are kept in cents (1299 means $12.99). Floating-point numbers cannot represent most decimal fractions exactly, so sums drift (0.1 + 0.2 is not 0.3). Integers add exactly. Convert to dollars only when displaying. (DecimalField is the other correct choice.)

Snapshot the price. OrderItem.unit_price_cents copies the book's price when the order is placed. If you read the price from the book later, raising it next month would change what customers paid last month.

Sessions store JSON. Django serializes the session as JSON. JSON object keys are always strings, so a cart saved as {1: 2} comes back as {"1": 2}. A cart that mixes integer and string keys is a classic source of "item added twice" bugs. The cart class below converts to str once, at the edge.

Step 1: the cart as plain Python

The cart does not need a database for its own logic: it needs a place to keep data (the session, which behaves like a dictionary), the catalog's price and stock, and rules. Writing it first with a plain dictionary as the "session" and a small catalog dictionary lets you test the rules in isolation. The rules are:

  • Adding more copies than the stock allows limits the quantity to the stock.
  • Setting a quantity of zero removes the line.
  • Totals are computed from current prices, in integer cents.
Python A shopping cart class you can test without a database

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The totals are exact because every price is an integer. The JSON round trip shows that the keys stay strings and the cart keeps working after the session is saved and loaded.

Step 2: the checkout is a transaction

Placing an order changes several tables at once: a new Order, several OrderItem rows and the stock column of each book. These changes must all succeed or all fail. That is exactly what transaction.atomic() provides (see Transactions and Concurrency).

The stock check deserves care. This looks right but is not:

Python
if book.stock >= quantity:      # check
    book.stock -= quantity      # ...time passes...
    book.save()                 # write

Between the check and the write, another request can buy the same copies, and the stock goes negative. The safe version is a single conditional UPDATE:

Python
updated = Book.objects.filter(pk=book.pk, stock__gte=quantity).update(stock=F("stock") - quantity)
if not updated:
    raise OutOfStock(...)

The database only decrements the stock if enough copies are still there, and tells you how many rows it changed. Zero means somebody else got there first. (On PostgreSQL you can alternatively lock the rows with select_for_update(), which SQLite ignores.)

When OutOfStock is raised inside the atomic() block, Django rolls back the whole block: the order row, any items already created and any stock already decremented for earlier lines.

The reports use annotate() and Sum() with an expression that multiplies two columns, so revenue is computed by the database in one query (Aggregation and Annotation).

Step 3: the whole store, live

The script has everything: settings with signed-cookie sessions, models, cart, views for the catalog, cart and checkout, the sales reports, a walkthrough, and tests. The walkthrough is the best part to read first: it shows a successful purchase, a failed purchase whose first line must be rolled back, and the reports.

Python Bookstore: cart, checkout transaction, reports and tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Study the middle of the output. The first checkout succeeded and emptied the cart. In the late checkout, the first line (a book that was still in stock) was processed before the second line failed, but afterwards the stock of that book is unchanged and no order was saved. That is the rollback at work, and test_failed_checkout_rolls_back_everything locks the behavior in.

The report queries run in the database. sales_by_book returns one row per sold book with units and revenue, sorted by revenue; sales_by_author rolls the same data up one more relation. Filtering with units__isnull=False hides books that never sold, which a plain annotate would otherwise list with None.

From JSON to a real storefront

The views return JSON to keep the focus on logic. In a real shop the same functions feed templates:

  • A context processor can put the cart count in every page header.
  • The catalog uses a ListView with filtering and pagination, and select_related("author") to avoid N+1 queries (query performance).
  • Checkout becomes a form with validation, protected by CSRF; the JSON views above skip CSRF only because the test client does not enforce it. In production keep CsrfViewMiddleware on.
  • Payment is handled by a provider such as Stripe: create the order as pending, send the customer to the payment page, and mark it paid when the provider calls your webhook. Never trust a price sent from the browser; always recompute totals on the server, as Cart.total_cents() does.
  • Use database sessions or a cache-backed session store once carts get large, because signed-cookie sessions are limited to about 4 KB (sessions).
  • When a visitor logs in, merge the anonymous cart into their saved cart.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the project store prices as integer cents?

    Integers add exactly, so 10 + 20 is always 30. Convert to dollars only when displaying the value.
  2. 2. Why does OrderItem copy unit_price_cents from the book?

    An order is a historical record. Reading the price from the book later would rewrite history whenever the price changes.
  3. 3. What makes Book.objects.filter(pk=..., stock__gte=quantity).update(stock=F('stock') - quantity) safer than checking book.stock in Python and saving?

    A read-then-write sequence leaves a gap in which another request can change the stock. A conditional UPDATE does both steps at once and reports how many rows changed.
  4. 4. A checkout adds three order items and fails on the fourth. What happens inside transaction.atomic()?

    An exception leaving an atomic block rolls back every change made inside it, so the database never holds a half-finished order.
  5. 5. A cart is saved in the session as {1: 2}. What will you read back after the session is stored as JSON?

    JSON object keys are always strings, so the integer key becomes "1". Using string keys from the start avoids mismatches.

Summary

  • Store money as integer cents and snapshot the price on each order item.
  • A session cart is a dictionary of {"book id": quantity}; session data is JSON, so use string keys.
  • Limit cart quantities to the stock, and recompute totals on the server from the database, never from browser input.
  • Checkout belongs in transaction.atomic(); any exception rolls back the order, items and stock changes together.
  • Protect stock with a conditional update(stock=F("stock") - n) and inspect the number of rows changed.
  • annotate with Sum(F(...) * F(...)) computes revenue per book or author in the database, and aggregate gives store-wide totals.
  • Tests for rollback, price snapshots and stock limits protect the rules that cost money when they break.

Next lesson: Project: Polls App.