Replies: 7 comments
-
|
For relationship cascades to work your related entities should be loaded first async def main():
async with engine.connect() as connection:
await connection.run_sync(SQLModel.metadata.drop_all)
await connection.run_sync(SQLModel.metadata.create_all)
await connection.commit()
# Seed the data
async with async_sessionmaker.begin() as session:
session.add(
User(
name="Doctor",
addresses=[Address(), Address()],
)
)
async with async_sessionmaker.begin() as session:
stmt = select(User).options(joinedload(User.addresses))
user = await session.scalar(stmt)
await session.delete(user) |
Beta Was this translation helpful? Give feedback.
-
|
@ThirVondukr I am aware that we need to load the relation manually but I am asking if there is another way, since usually you may have many relations it is not practical to load each of them. Also keep in mind that these children will have other children under them that need to be loaded as well to apply the cascades. I think using the |
Beta Was this translation helpful? Give feedback.
-
|
Your data integrity should be handled on DB side as much as possible 😉 |
Beta Was this translation helpful? Give feedback.
-
|
maybe you can try to add |
Beta Was this translation helpful? Give feedback.
-
|
@wangxin688 thanks I didn't know about this flag, but it still won't fix the problem because you would need to add a |
Beta Was this translation helpful? Give feedback.
-
That's true, you need define cascade action in Column level, db natively action is always a better choice for me. |
Beta Was this translation helpful? Give feedback.
-
|
This really looks a bit unexpected. But, there is the same issue when pure SQLAlchemy is used (see in the details): Detailsimport asyncio
from typing import List
from sqlalchemy import ForeignKey, String, select
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, Relationship, mapped_column
class Base(DeclarativeBase):
pass
class Address(Base):
__tablename__ = "addresses"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
user: Mapped["User"] = Relationship(back_populates="addresses", lazy="noload")
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100), nullable=False)
addresses: Mapped[List["Address"]] = Relationship(
back_populates="user", cascade="all", lazy="noload"
)
engine = create_async_engine("sqlite+aiosqlite:///")
async def main():
async with engine.connect() as connection:
await connection.run_sync(Base.metadata.create_all)
async with AsyncSession(engine) as session:
u = User(name="user 1", addresses=[Address(), Address()])
session.add(u)
await session.commit()
async with AsyncSession(engine) as session:
res = await session.execute(select(Address))
assert len(res.all()) == 2
async with AsyncSession(engine) as session:
u = await session.get(User, 1)
# u = await session.get(User, 1, options=[selectinload(User.addresses)])
await session.delete(u)
await session.commit()
async with AsyncSession(engine) as session:
res = await session.execute(select(Address))
addresses = list(res.all())
assert len(addresses) == 0, len(addresses) # AssertionError: 2
if __name__ == "__main__":
asyncio.run(main()) |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
When using
lazy='noload'in the relationship arguments it loads the user object withaddresses: []so there are no addresses to apply the cascade to, you always have toselectinloadorjoinedloadso that when deleting the object it works.Am I misunderstanding or doing it wrong because that looks too much work just to delete an object, specially if it has too many relations.
Operating System
Linux, Windows
Operating System Details
No response
SQLModel Version
0.0.8
Python Version
3.11
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions