Defining order states and allowed transitions

Backend models often accumulate boolean flags over time:

# The anti-pattern:
class Order(models.Model):
    is_placed = models.BooleanField(default=False)
    is_paid = models.BooleanField(default=False)
    is_shipped = models.BooleanField(default=False)
    is_cancelled = models.BooleanField(default=False)
    is_refunded = models.BooleanField(default=False)

Five booleans allow $2^5 = 32$ combinations, including broken ones such as is_placed=False, is_shipped=True, and is_refunded=True.

Explicit States

A finite state machine narrows the model to named states and allowed transitions:

class OrderState(models.TextChoices):
    DRAFT = "draft", "Draft"
    PENDING = "pending", "Pending Payment"
    PAID = "paid", "Paid"
    SHIPPED = "shipped", "Shipped"
    CANCELLED = "cancelled", "Cancelled"

class Order(models.Model):
    state = models.CharField(
        max_length=20,
        choices=OrderState.choices,
        default=OrderState.DRAFT
    )

Guarded Transitions

I put state transitions inside model methods with explicit checks rather than updating flags across views:

def mark_paid(self):
    if self.state != OrderState.PENDING:
        raise ValueError(f"Cannot transition to PAID from {self.state}")
    self.state = OrderState.PAID
    self.save(update_fields=["state"])

Making invalid states impossible to store prevents contradictory order bugs at the database layer.

← Journal