Handling Complex Business Logic in Django
Design Django domain services for financial calculations and state changes. Make rounding, transaction boundaries, concurrency, and retry behavior explicit.
A discount rule starts as three lines in a serializer. Then it depends on customer tier, quantity, an invoice’s currency, and whether a credit has already been issued. The next endpoint copies it with slightly different rounding. Your application now has two definitions of the same business operation.

Complex logic needs an owner and a contract. Separate deterministic calculations from the service that loads records, checks business invariants, and persists a state transition. The examples use Python Decimal and Django 5.2; the model names represent application-specific contracts.
Step 1: Write the Calculation as a Pure Function
from dataclasses import dataclass
from decimal import Decimal, ROUND_HALF_UP
@dataclass(frozen=True)
class LineTotal:
subtotal: Decimal
discount: Decimal
payable: Decimal
def price_line(*, unit_price: Decimal, quantity: int,
discount_rate: Decimal) -> LineTotal:
if not unit_price.is_finite() or not discount_rate.is_finite():
raise ValueError('Amounts must be finite')
if unit_price < 0 or quantity < 1:
raise ValueError('Invalid price or quantity')
if not Decimal('0') <= discount_rate <= Decimal('1'):
raise ValueError('Invalid discount rate')
cent = Decimal('0.01')
subtotal = (unit_price * quantity).quantize(cent, ROUND_HALF_UP)
discount = (subtotal * discount_rate).quantize(cent, ROUND_HALF_UP)
return LineTotal(subtotal, discount, subtotal - discount)This example explicitly chooses a two-decimal currency, line-level discount rounding, and ROUND_HALF_UP. Those are product rules, not universal accounting rules. A currency with another minor unit or an invoice-level rounding policy needs a different contract.
Construct Decimal inputs from validated strings or exact decimal values rather than binary floats. Python’s decimal module supports decimal arithmetic and explicit rounding, but you still own the precision and rounding choices.
Python decimal arithmetic and rounding
Step 2: Put State Changes in a Domain Service
from django.db import transaction
from billing.models import Invoice, Credit
@transaction.atomic
def issue_credit(*, tenant_id, invoice_id, amount):
invoice = Invoice.objects.select_for_update().get(
tenant_id=tenant_id, pk=invoice_id
)
invoice.assert_credit_allowed(amount)
credit = Credit.objects.create(invoice=invoice, amount=amount)
invoice.credited_amount += amount
invoice.save(update_fields=['credited_amount'])
return creditThe invariant check belongs to the operation: the amount must be positive, finite, in the correct currency, and within the remaining refundable balance. The authenticated entry point must also establish that the actor can issue this credit for the selected tenant.
Step 3: Design for Concurrency and Retries
On a database that supports row locking, select_for_update inside a transaction coordinates competing updates to the same invoice. Every writer must follow the same locking or equivalent concurrency policy. SQLite does not provide the same row-lock behavior, so test the critical path against the production database backend.
Django select_for_update behavior
A lock does not identify a retried request. Accept a stable idempotency key and enforce uniqueness within its business scope, such as tenant plus operation plus key. Store the resulting credit reference and reject reuse of the same key with a different payload. Two successful HTTP attempts should resolve to one intended credit.
External Effects Have Another Boundary
A local database transaction cannot undo a refund already accepted by a remote provider. Record a pending operation, call the provider with its supported idempotency mechanism, and reconcile the outcome. For durable follow-up events, an outbox can record delivery intent in the same database transaction.
Use on_commit for correctly timed best-effort callbacks, while recognizing that process failure can still interrupt delivery after the commit. Keep this distinction explicit in the service contract.
Related: Commit First, Notify Later
Test Invariants, Not Folder Names
Test calculation boundaries with fixed inputs: zero discount, maximum discount, rounding ties, invalid amounts, and a currency-policy mismatch. Test state transitions with duplicate requests, competing credits, and a provider timeout. The value of a domain service is that the business rule stays the same whether the caller is an API view, a task, or an administrative command.