Open any Django codebase that's older than eighteen months and find the most important thing the business does. Placing an order. Approving a loan. Issuing a refund. Now find where that logic lives. Nine times out of ten it's smeared across a view, a serializer's create(), two model save() overrides and a post_save signal somebody added on a Friday.
Here's the position: views and serializers are adapters, not homes. A view translates HTTP into a function call. A serializer translates JSON into Python values. Neither should know what an order is. Put the rules in plain Python functions that take plain arguments, and your app gets easier to test, easier to read and much easier to change.
How it goes wrong
Nobody decides to put business logic in a serializer. It happens because Django and DRF make the wrong place the convenient place:
ModelSerializer.create()is right there. It already has validated data and a model. Adding "and also charge the card" is one line.- Views have the request. The user, the headers, the session. So the logic that needs the user ends up next to the request.
- Signals look clean. Until nobody can tell you what happens when an
Orderis saved, because the answer is spread over four apps. - Fat models sound like good advice. And they are, for logic about one row. They fall apart when a use case touches five models and an external API.
The result is logic you can only reach through HTTP. Want to place an order from a management command, a Celery task or a data migration? You either fake a request or copy the code. Both are bad.
Before: the serializer that does everything
This is a composite of code I've seen many times. It works. It's also a trap.
class OrderSerializer(serializers.ModelSerializer):
items = OrderItemSerializer(many=True)
class Meta:
model = Order
fields = ["id", "items", "total"]
read_only_fields = ["total"]
def create(self, validated_data):
items = validated_data.pop("items")
user = self.context["request"].user
order = Order.objects.create(customer=user, total=0)
total = Decimal("0")
for item in items:
product = item["product"]
if product.stock < item["quantity"]:
raise serializers.ValidationError("Out of stock")
product.stock -= item["quantity"]
product.save()
OrderItem.objects.create(order=order, product=product,
quantity=item["quantity"],
price=product.price)
total += product.price * item["quantity"]
order.total = total
order.save()
stripe.PaymentIntent.create(amount=int(total * 100), currency="aud",
customer=user.stripe_id)
send_mail("Order received", f"Order {order.id}", None, [user.email])
return order
Count the problems:
- No transaction. If the payment call fails, you've already decremented stock and created a half-built order.
- A race on stock. Two requests read
stock = 1, both pass the check, both save0. You've sold the same item twice. - The email goes out before anything is committed. The customer gets "Order received" for an order that may roll back.
- The rules are tied to
self.context["request"]. You can't call this without an HTTP request, or a fake one. - A
ValidationErrorfor a business rule. "Out of stock" isn't malformed input. It's a domain outcome, and it deserves its own type. - Testing it means testing everything. To check the stock rule you need a client, auth, JSON and a mocked Stripe.
After: a service function
Make a services.py (or orders/services/place_order.py when it grows) with a plain function. Keyword-only arguments, explicit dependencies, a clear return type.
# orders/services.py
from dataclasses import dataclass
from decimal import Decimal
from django.db import transaction
from django.db.models import F
from orders.models import Order, OrderItem, Product
from orders.notifications import send_order_received
class OutOfStock(Exception):
def __init__(self, product_id: int) -> None:
super().__init__(f"Product {product_id} is out of stock")
self.product_id = product_id
@dataclass(frozen=True)
class LineRequest:
product_id: int
quantity: int
def place_order(*, customer, lines: list[LineRequest], payments) -> Order:
with transaction.atomic():
ids = sorted({line.product_id for line in lines})
locked = (Product.objects.select_for_update()
.filter(pk__in=ids).order_by("pk"))
products = {product.pk: product for product in locked}
order = Order.objects.create(customer=customer, total=Decimal("0"))
total = Decimal("0")
for line in lines:
product = products[line.product_id]
if product.stock < line.quantity:
raise OutOfStock(product.pk)
Product.objects.filter(pk=product.pk).update(
stock=F("stock") - line.quantity)
OrderItem.objects.create(order=order, product=product,
quantity=line.quantity,
price=product.price)
total += product.price * line.quantity
order.total = total
order.save(update_fields=["total"])
payments.charge(customer=customer, amount=total,
reference=str(order.pk))
transaction.on_commit(lambda: send_order_received(order.pk))
return order
What changed:
transaction.atomic()wraps the whole use case. Any exception, including a payment failure, rolls back the stock and the order.select_for_update()locks the product rows, in a stable order, so two orders for the last item can't both win.F("stock") - quantitydoes the decrement in the database rather than in Python.transaction.on_commit()sends the email only once the order really exists.paymentsis passed in. In production it's a thin wrapper around your provider. In tests it's a fake. Nomock.patchon a module path.OutOfStockis a real exception. The caller decides what it means: a 409 for the API, a message in the admin, a log line in a batch job.
One honest caveat: charging a card inside a database transaction holds row locks while you wait on a network call. For a low-volume shop that's fine. At scale you'd split it into "reserve, then charge, then confirm" steps. The point is that once the logic lives in one function, that refactor is one file, not a hunt through serializers and signals.
The view and serializer get boring
class PlaceOrderInput(serializers.Serializer):
items = LineInput(many=True)
class PlaceOrderView(APIView):
permission_classes = [IsAuthenticated]
def post(self, request):
data = PlaceOrderInput(data=request.data)
data.is_valid(raise_exception=True)
lines = [LineRequest(**item) for item in data.validated_data["items"]]
try:
order = place_order(customer=request.user, lines=lines,
payments=get_payment_gateway())
except OutOfStock as exc:
return Response(
{"error": "out_of_stock", "product_id": exc.product_id},
status=status.HTTP_409_CONFLICT)
return Response(OrderOutput(order).data,
status=status.HTTP_201_CREATED)
The serializer checks shape: is quantity an integer, is product_id present. The view maps HTTP to a call and exceptions to status codes. That's all either of them should ever do. Boring is the goal.
Testing without HTTP
Now the important rules are tested directly:
class FakePayments:
def __init__(self, fail: bool = False) -> None:
self.fail = fail
self.charges: list[tuple[object, Decimal]] = []
def charge(self, *, customer, amount: Decimal, reference: str) -> None:
if self.fail:
raise RuntimeError("card declined")
self.charges.append((customer, amount))
def test_payment_failure_rolls_back_stock(db, customer, product_with_stock):
product = product_with_stock(stock=3, price=Decimal("10.00"))
with pytest.raises(RuntimeError):
place_order(customer=customer,
lines=[LineRequest(product.pk, 2)],
payments=FakePayments(fail=True))
product.refresh_from_db()
assert product.stock == 3
assert not Order.objects.exists()
No client, no JSON, no auth setup, no patching. The test reads like the rule it protects. Keep one or two API tests per endpoint to check the wiring, and put the volume of your tests at the service level.
Rules I actually follow
- One use case, one function.
place_order,cancel_order,refund_order. Name them after what the business says, not after HTTP verbs. - Keyword-only arguments.
place_order(customer=..., lines=...)can't be called with arguments in the wrong order. - Services take values, not requests. Pass
request.user, neverrequest. - Reads can be selectors. A
selectors.pywith query functions keeps complex querysets out of views too. SimpleModel.objects.filter()calls in a view are fine. Don't build ceremony for one-liners. - Models keep row-level logic.
order.is_refundable()belongs on the model. "Refund this order, restock, notify the warehouse and reverse the charge" does not. - No signals for business flow. Signals are for decoupled side concerns like cache busting. If it's part of the use case, call it explicitly.
- Don't build a framework. No abstract base
Serviceclass, no command bus, no dependency injection container. Functions and modules. Python already has them.
When this is overkill
A CRUD admin over a few tables doesn't need a service layer. If a ModelViewSet really is the whole feature, enjoy it. The moment an endpoint does more than save what it was given, such as touching a second model, calling an external API or enforcing a rule the business cares about, move it into a function. It takes ten minutes now, or a week later.
Bottom line
Django gives you an excellent ORM and a decent request cycle. It doesn't give you a place for your domain, so you have to make one. Thin views, dumb serializers, plain service functions. Your rules become callable from anywhere, testable in milliseconds and readable by the next developer, who is usually you, six months from now, at 11 pm, during an incident.