sqlmodel/docs/tutorial/connect/remove-data-connections.md

2.7 KiB
Raw Blame History

Remove Data Connections

We currently have a team table:

idnameheadquarters
1PreventersSharp Tower
2Z-ForceSister Margarets Bar

And a hero table:

idnamesecret_nameageteam_id
1DeadpondDive Wilsonnull2
2Rusty-ManTommy Sharp481
3Spider-BoyPedro Parqueadornull1

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. 💥