You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The session automatically handles transaction management, ensuring that database operations are atomic and consistent.
295
+
296
+
#### Cascade deletes
297
+
298
+
Cascade deletes (in which deleting a record from one table deletes related records from another table) can be handled at either the ORM level or the database level. This template handles cascade deletes at the ORM level, via SQLModel relationships. Inside a SQLModel `Relationship`, we set:
299
+
300
+
```python
301
+
sa_relationship_kwargs={
302
+
"cascade": "all, delete-orphan"
303
+
}
304
+
```
305
+
306
+
This tells SQLAlchemy to cascade all operations (e.g., `SELECT`, `INSERT`, `UPDATE`, `DELETE`) to the related table. Since this happens through the ORM, we need to be careful to do all our database operations through the ORM using supported syntax. That generally means loading database records into Python objects and then deleting those objects rather than deleting records in the database directly.
307
+
308
+
For example,
309
+
310
+
```python
311
+
session.exec(delete(Role))
312
+
```
313
+
314
+
will not trigger the cascade delete. Instead, we need to select the role objects and then delete them:
315
+
316
+
```python
317
+
for role in session.exec(select(Role)).all():
318
+
session.delete(role)
319
+
```
320
+
321
+
This is slower than deleting the records directly, but it makes [many-to-many relationships](https://sqlmodel.tiangolo.com/tutorial/many-to-many/create-models-with-link/#create-the-tables) much easier to manage.
0 commit comments