2.7 KiB
Remove Data Connections
We currently have a team
table:
id | name | headquarters |
---|---|---|
1 | Preventers | Sharp Tower |
2 | Z-Force | Sister Margaret’s Bar |
And a hero
table:
id | name | secret_name | age | team_id |
---|---|---|---|---|
1 | Deadpond | Dive Wilson | null | 2 |
2 | Rusty-Man | Tommy Sharp | 48 | 1 |
3 | Spider-Boy | Pedro Parqueador | null | 1 |
Let's see how to remove connections between rows in tables.
We will continue with the code from the previous chapter.
👀 Full file preview
{!./docs_src/tutorial/connect/update/tutorial001.py!}
Break a Connection
We don't really have to delete anything to break a connection. We can just assign None
to the foreign key, in this case, to the team_id
.
Let's say Spider-Boy is tired of the lack of friendly neighbors and wants to get out of the Preventers.
We can simply set the team_id
to None
, and now it doesn't have a connection with the team:
# Code above omitted 👆
{!./docs_src/tutorial/connect/delete/tutorial001.py[ln:31-32]!}
# Previous code here omitted 👈
{!./docs_src/tutorial/connect/delete/tutorial001.py[ln:68-72]!}
# Code below omitted 👇
👀 Full file preview
{!./docs_src/tutorial/connect/delete/tutorial001.py!}
Again, we just assign a value to that field attribute team_id
, now the value is None
, which means NULL
in the database. Then we add()
the hero to the session, and then commit()
.
Next we refresh()
it to get the recent data, and we print it.
Running that in the command line will output:
$ python app.py
// Previous output omitted 😉
// Update the hero
INFO Engine UPDATE hero SET team_id=? WHERE hero.id = ?
INFO Engine [cached since 0.07753s ago] (None, 3)
// Commit the session
INFO Engine COMMIT
// Automatically start a new transaction
INFO Engine BEGIN (implicit)
// Refresh the hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.1661s ago] (3,)
// Print the hero without a team
No longer Preventer: id=3 secret_name='Pedro Parqueador' team_id=None name='Spider-Boy' age=None
That's it, we now removed a connection between rows in different tables by unsetting the foreign key column. 💥