Open
Description
First Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn't find it.
- I searched the SQLModel documentation, with the integrated search.
- I already searched in Google "How to X in SQLModel" and didn't find any information.
- I already read and followed all the tutorial in the docs and didn't find an answer.
- I already checked if it is not related to SQLModel but to Pydantic.
- I already checked if it is not related to SQLModel but to SQLAlchemy.
Commit to Help
- I commit to help with one of those options 👆
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