Removing orphanated entries from the database after the parent is deleted #1011
-
First Check
Commit to Help
Example Codeclass Product(SQLModel, table=True):
"""Products model."""
__allow_unmapped__ = True
id: UUID = Field(default=uuid.uuid4(), primary_key=True, nullable=False)
name: str = Field(nullable=False)
date: datetime = Field(default=datetime.now(timezone.utc), nullable=False)
prices: list[Prices] = Relationship(
back_populates="product",
sa_relationship_kwargs={"cascade": "all, delete, delete-orphan"},
)
def __init__(self, name: str) -> None:
"""Initialize the product model."""
self.id = uuid.uuid4()
self.name = name
self.date = datetime.now(timezone.utc)
def delete_product(self) -> Response:
"""Delete the product from the database."""
with Session(engine) as session:
session.delete(self)
session.commit()
return self
class Prices(SQLModel, table=True):
"""Products prices model."""
__allow_unmapped__ = True
id: UUID = Field(default=uuid.uuid4(), primary_key=True)
product_id: UUID = Field(foreign_key="product.id")
price_list: list[float] = Field(sa_column=Column(ARRAY(Float)))
date: datetime = Field(default=datetime.now(timezone.utc), nullable=False)
product: Product | None = Relationship(back_populates="prices")
def __init__(self, product_id: UUID, price_list: list[float]) -> None:
"""Initialize the price model."""
self.id = uuid.uuid4()
self.product_id = product_id
self.price_list = price_list
self.date = datetime.now(timezone.utc) DescriptionWhat I am trying to achieve is to have the prices deleted the second I remove a product, as there is no point in having them without a parent. I have tried different solutions yet to no avail. Operating SystemLinux Operating System DetailsDocker SQLModel Version0.0.19 Python Version3.12.3 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Answered by
YuriiMotov
Aug 20, 2025
Replies: 1 comment
-
Docs about Cascade Delete Relationships: https://sqlmodel.tiangolo.com/tutorial/relationship-attributes/cascade-delete-relationships/ This should help |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
YuriiMotov
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Docs about Cascade Delete Relationships: https://sqlmodel.tiangolo.com/tutorial/relationship-attributes/cascade-delete-relationships/
This should help