From 2691708304ccd5b32898d9b856b1f521bf0a3ac6 Mon Sep 17 00:00:00 2001 From: Piotr Oleszczyk Date: Sat, 28 Feb 2026 22:48:00 +0100 Subject: [PATCH] fix(models): cascade delete inventory rows when product is deleted SQLAlchemy was nulling out product_id on ProductInventory rows instead of deleting them. Added cascade="all, delete-orphan" to the ORM relationship and ondelete="CASCADE" to the FK field. Co-Authored-By: Claude Sonnet 4.6 --- backend/innercontext/models/product.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/backend/innercontext/models/product.py b/backend/innercontext/models/product.py index 9659826..bb5dc0b 100644 --- a/backend/innercontext/models/product.py +++ b/backend/innercontext/models/product.py @@ -202,7 +202,10 @@ class Product(ProductBase, table=True): ), ) - inventory: list["ProductInventory"] = Relationship(back_populates="product") + inventory: list["ProductInventory"] = Relationship( + back_populates="product", + sa_relationship_kwargs={"cascade": "all, delete-orphan"}, + ) @field_validator("product_effect_profile", mode="before") @classmethod @@ -378,7 +381,7 @@ class ProductInventory(SQLModel, table=True): __domains__: ClassVar[frozenset[Domain]] = frozenset({Domain.SKINCARE}) id: UUID = Field(default_factory=uuid4, primary_key=True) - product_id: UUID = Field(foreign_key="products.id", index=True) + product_id: UUID = Field(foreign_key="products.id", index=True, ondelete="CASCADE") is_opened: bool = Field(default=False) opened_at: date | None = Field(default=None)