Django DRF - Part 01 - ECommerce Model Architecture
Technical Staff
FilterB Editorial

Before diving into code, it is essential to visualize how these entities interact. In a standard E-commerce flow:
- A User places an Order.
- An Order can contain multiple Products.
- An OrderItem acts as the "link," tracking exactly how many of a specific product were bought in a specific order.
Implementation Code
# 1. Product Catalog
class Product(models.Model):
name = models.CharField(max_length=200)
description = models.TextField()
# DecimalField is critical for financial accuracy
price = models.DecimalField(max_digits=10, decimal_places=2)
stock = models.PositiveIntegerField()
image = models.ImageField(upload_to='products/', blank=True, null=True)
@property
def in_stock(self):
return self.stock > 0
def __str__(self):
return self.name
# 2. Order Management
class Order(models.Model):
class StatusChoices(models.TextChoices):
PENDING = 'Pending'
CONFIRMED = 'Confirmed'
CANCELLED = 'Cancelled'
# UUID prevents predictable Order IDs
order_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders')
created_at = models.DateTimeField(auto_now_add=True)
status = models.CharField(
max_length=10,
choices=StatusChoices.choices,
default=StatusChoices.PENDING
)
# Linking products via the OrderItem helper table
products = models.ManyToManyField(Product, through="OrderItem", related_name='orders')
def __str__(self):
return f"Order {self.order_id} by {self.user.username}"
# 3. Transaction Details (The 'Through' Table)
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField()
@property
def item_subtotal(self):
return self.product.price * self.quantity
def __str__(self):
return f"{self.quantity} x {self.product.name} (Order: {self.order.order_id})"




