Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions backend/apps/catalog/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from django.contrib import admin

from .models import Category, Product, ProductImage
from .models import (
Category,
LaptopSpecification,
MobileSpecification,
Product,
ProductImage,
)


class ProductImageInline(admin.TabularInline):
Expand All @@ -9,6 +15,18 @@ class ProductImageInline(admin.TabularInline):
fields = ("image", "alt_text", "display_order")


class LaptopSpecificationInline(admin.StackedInline):
model = LaptopSpecification
extra = 0
max_num = 1


class MobileSpecificationInline(admin.StackedInline):
model = MobileSpecification
extra = 0
max_num = 1


@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
list_display = ("name", "slug", "is_active", "display_order")
Expand All @@ -23,13 +41,15 @@ class ProductAdmin(admin.ModelAdmin):
list_display = (
"name",
"category",
"product_type",
"brand",
"price",
"stock_quantity",
"status",
"is_featured",
)
list_editable = ("price", "stock_quantity", "status", "is_featured")
list_filter = ("status", "is_featured", "category")
list_filter = ("product_type", "status", "is_featured", "category")
search_fields = ("name", "sku", "slug")
prepopulated_fields = {"slug": ("name",)}
inlines = (ProductImageInline,)
inlines = (ProductImageInline, LaptopSpecificationInline, MobileSpecificationInline)
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Generated by Django 6.0.7 on 2026-08-17 18:39

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("catalog", "0002_productimage_image"),
]

operations = [
migrations.AddField(
model_name="product",
name="brand",
field=models.CharField(blank=True, max_length=80),
),
migrations.AddField(
model_name="product",
name="product_type",
field=models.CharField(
choices=[("laptop", "Laptop"), ("mobile", "Mobile")],
default="laptop",
max_length=16,
),
),
migrations.CreateModel(
name="LaptopSpecification",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("processor", models.CharField(max_length=120)),
("ram_gb", models.PositiveSmallIntegerField()),
("storage_gb", models.PositiveIntegerField()),
(
"display_size_inches",
models.DecimalField(decimal_places=1, max_digits=3),
),
("graphics", models.CharField(blank=True, max_length=120)),
(
"product",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="laptop_specification",
to="catalog.product",
),
),
],
),
migrations.CreateModel(
name="MobileSpecification",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("ram_gb", models.PositiveSmallIntegerField()),
("storage_gb", models.PositiveIntegerField()),
("camera_megapixels", models.PositiveSmallIntegerField()),
(
"network",
models.CharField(
choices=[("4g", "4G"), ("5g", "5G")], max_length=2
),
),
("battery_mah", models.PositiveIntegerField()),
(
"product",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="mobile_specification",
to="catalog.product",
),
),
],
),
]
54 changes: 54 additions & 0 deletions backend/apps/catalog/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ def __str__(self) -> str:


class Product(TimeStampedModel):
class Type(models.TextChoices):
LAPTOP = "laptop", "Laptop"
MOBILE = "mobile", "Mobile"

class Status(models.TextChoices):
DRAFT = "draft", "Draft"
PUBLISHED = "published", "Published"
Expand All @@ -38,6 +42,10 @@ class Status(models.TextChoices):
category = models.ForeignKey(
Category, on_delete=models.PROTECT, related_name="products"
)
product_type = models.CharField(
max_length=16, choices=Type.choices, default=Type.LAPTOP
)
brand = models.CharField(max_length=80, blank=True)
name = models.CharField(max_length=180)
slug = models.SlugField(unique=True)
sku = models.CharField(max_length=64, unique=True)
Expand Down Expand Up @@ -84,6 +92,52 @@ def clean(self) -> None:
)


class LaptopSpecification(models.Model):
product = models.OneToOneField(
Product, on_delete=models.CASCADE, related_name="laptop_specification"
)
processor = models.CharField(max_length=120)
ram_gb = models.PositiveSmallIntegerField()
storage_gb = models.PositiveIntegerField()
display_size_inches = models.DecimalField(max_digits=3, decimal_places=1)
graphics = models.CharField(max_length=120, blank=True)

def clean(self) -> None:
super().clean()
if self.product.product_type != Product.Type.LAPTOP:
raise ValidationError(
{"product": "Laptop details require a laptop product."}
)

def __str__(self) -> str:
return f"Laptop details for {self.product}"


class MobileSpecification(models.Model):
class Network(models.TextChoices):
FOUR_G = "4g", "4G"
FIVE_G = "5g", "5G"

product = models.OneToOneField(
Product, on_delete=models.CASCADE, related_name="mobile_specification"
)
ram_gb = models.PositiveSmallIntegerField()
storage_gb = models.PositiveIntegerField()
camera_megapixels = models.PositiveSmallIntegerField()
network = models.CharField(max_length=2, choices=Network.choices)
battery_mah = models.PositiveIntegerField()

def clean(self) -> None:
super().clean()
if self.product.product_type != Product.Type.MOBILE:
raise ValidationError(
{"product": "Mobile details require a mobile product."}
)

def __str__(self) -> str:
return f"Mobile details for {self.product}"


class ProductImage(TimeStampedModel):
product = models.ForeignKey(
Product, on_delete=models.CASCADE, related_name="images"
Expand Down
53 changes: 51 additions & 2 deletions backend/apps/catalog/serializers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from rest_framework import serializers

from .models import Category, Product, ProductImage
from .models import (
Category,
LaptopSpecification,
MobileSpecification,
Product,
ProductImage,
)


class CategorySerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -34,6 +40,8 @@ class Meta:
"id",
"name",
"slug",
"product_type",
"brand",
"short_description",
"price",
"compare_at_price",
Expand All @@ -53,6 +61,47 @@ def get_primary_image(self, product: Product) -> str | None:

class ProductDetailSerializer(ProductListSerializer):
images = ProductImageSerializer(many=True, read_only=True)
specifications = serializers.SerializerMethodField()

class Meta(ProductListSerializer.Meta):
fields = ProductListSerializer.Meta.fields + ("description", "sku", "images")
fields = ProductListSerializer.Meta.fields + (
"description",
"sku",
"specifications",
"images",
)

def get_specifications(self, product: Product) -> dict | None:
if product.product_type == Product.Type.LAPTOP:
specification = getattr(product, "laptop_specification", None)
if specification is None:
return None
return LaptopSpecificationSerializer(specification).data
specification = getattr(product, "mobile_specification", None)
if specification is None:
return None
return MobileSpecificationSerializer(specification).data


class LaptopSpecificationSerializer(serializers.ModelSerializer):
class Meta:
model = LaptopSpecification
fields = (
"processor",
"ram_gb",
"storage_gb",
"display_size_inches",
"graphics",
)


class MobileSpecificationSerializer(serializers.ModelSerializer):
class Meta:
model = MobileSpecification
fields = (
"ram_gb",
"storage_gb",
"camera_megapixels",
"network",
"battery_mah",
)
82 changes: 81 additions & 1 deletion backend/apps/catalog/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,13 @@
import pytest
from rest_framework.test import APIClient

from apps.catalog.models import Category, Product, ProductImage
from apps.catalog.models import (
Category,
LaptopSpecification,
MobileSpecification,
Product,
ProductImage,
)


def create_product(
Expand Down Expand Up @@ -85,3 +91,77 @@ def test_product_api_uses_minio_url_for_uploaded_images() -> None:
"display_order": 0,
},
]


@pytest.mark.django_db
def test_product_api_filters_laptops_with_common_and_laptop_specific_filters() -> None:
category = Category.objects.create(name="Laptops", slug="laptops")
laptop = create_product(category, slug="laptop", price=Decimal(30000000))
laptop.product_type = Product.Type.LAPTOP
laptop.brand = "Nexora"
laptop.stock_quantity = 2
laptop.save(update_fields=["product_type", "brand", "stock_quantity"])
LaptopSpecification.objects.create(
product=laptop,
processor="Core Ultra 7",
ram_gb=16,
storage_gb=1024,
display_size_inches=Decimal("14.0"),
)
lower_spec = create_product(category, slug="lower-spec", price=Decimal(20000000))
LaptopSpecification.objects.create(
product=lower_spec,
processor="Core i5",
ram_gb=8,
storage_gb=512,
display_size_inches=Decimal("15.6"),
)

response = APIClient().get(
"/api/v1/catalog/products/?type=laptop&brand=nexora&min_price=25000000"
"&ram_min=16&storage_min=1024&processor=ultra&in_stock=true"
)

assert response.status_code == 200
assert [item["slug"] for item in response.data["results"]] == ["laptop"]


@pytest.mark.django_db
def test_product_detail_and_mobile_filters_expose_mobile_specifications() -> None:
category = Category.objects.create(name="Mobiles", slug="mobiles")
mobile = create_product(category, slug="mobile", price=Decimal(18000000))
mobile.product_type = Product.Type.MOBILE
mobile.brand = "Nexora Mobile"
mobile.save(update_fields=["product_type", "brand"])
MobileSpecification.objects.create(
product=mobile,
ram_gb=12,
storage_gb=256,
camera_megapixels=50,
network=MobileSpecification.Network.FIVE_G,
battery_mah=5000,
)

list_response = APIClient().get(
"/api/v1/catalog/products/?type=mobile&ram_min=8&storage_min=128&network=5g"
)
detail_response = APIClient().get("/api/v1/catalog/products/mobile/")

assert list_response.status_code == 200
assert [item["slug"] for item in list_response.data["results"]] == ["mobile"]
assert detail_response.status_code == 200
assert detail_response.data["specifications"] == {
"ram_gb": 12,
"storage_gb": 256,
"camera_megapixels": 50,
"network": "5g",
"battery_mah": 5000,
}


@pytest.mark.django_db
def test_product_api_rejects_invalid_filter_values() -> None:
response = APIClient().get("/api/v1/catalog/products/?type=mobile&network=6g")

assert response.status_code == 400
assert "network" in response.data
Loading
Loading