2.6 KiB
Update Data Connections
At this point we 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 | null |
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. 💥