sqlmodel/docs/tutorial/connect/update-data-connections.md
Sebastián Ramírez 6d1d86ab85 📝 Add docs
2021-08-24 15:02:48 +02:00

2.6 KiB
Raw Blame History

Update Data Connections

At this point we 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 Parqueadornullnull

Some of these heroes are part of a team.

Now we'll see how to update those connections between rows tables.

We will continue with the code we used to create some heroes, and we'll update them.

👀 Full file preview
{!./docs_src/tutorial/connect/insert/tutorial001.py!}

Assign a Team to a Hero

Let's say that Tommy Sharp uses his "rich uncle" charms to recruit Spider-Boy to join the team of the Preventers, now we need to update our Spider-Boy hero object to connect it to the Preventers team.

Doing it is just like updating any other field:

# Code above omitted 👆

{!./docs_src/tutorial/connect/update/tutorial001.py[ln:31-32]!}
        
        # Previous code here omitted 👈

{!./docs_src/tutorial/connect/update/tutorial001.py[ln:62-66]!}

# Code below omitted 👇
👀 Full file preview
{!./docs_src/tutorial/connect/update/tutorial001.py!}

We can simply assign a value to that field attribute team_id, then 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 [generated in 0.00014s] (1, 3)
// Commit the session saving the changes
INFO Engine COMMIT
// Automatically start a new transaction
INFO Engine BEGIN (implicit)
// Refresh the hero data
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.08837s ago] (3,)

// Print the updated hero
Updated hero: id=3 secret_name='Pedro Parqueador' team_id=1 name='Spider-Boy' age=None

And now Spider-Boy has the team_id=1, which is the ID of the Preventers. 🎉

Let's now see how to remove connections in the next chapter. 💥