First Check
Commit to Help
Example Code
from typing import List, Optional
import sqlalchemy as sa
from sqlmodel import Field, Relationship, SQLModel
class Address(SQLModel, table=True):
__tablename__ = 'addresses'
id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
user_id: int = Field(foreign_key='users.id', nullable=False)
user: 'User' = Relationship(back_populates='addresses', sa_relationship_kwargs={'lazy':'noload'})
class User(SQLModel, table=True):
__tablename__ = 'users'
id: Optional[int] = Field(default=None, primary_key=True, nullable=False)
name: str = Field(max_length=100, nullable=False)
addresses: List['Address'] = Relationship(back_populates='user', sa_relationship_kwargs={'cascade': 'all, delete', 'lazy':'noload'})
# when doing a delete
async def remove_user(db: AsyncSession, *, id: int):
obj = await db.get(User, id)
await db.delete(obj)
await db.commit()
Description
When using lazy='noload' in the relationship arguments it loads the user object with addresses: [] so there are no addresses to apply the cascade to, you always have to selectinload or joinedload so 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
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