Deleting objects
Delete objects from a Baseten Postgres table.
"Let the past die. Kill it, if you have to." — Kylo Ren, Star Wars: The Last Jedi

Deleting a single object

To delete a single object, add the following to your code block:
1
session.delete(photo)
Copied!
To delete by id or another field, do the following:
1
session.query(RestaurantPhotoLabel).filter_by(id=6).delete()
Copied!
However, this delete will not get cascaded, therefore if RestaurantPhotoLabel was a foreign key for some other table, those RestaurantPhotoLabel objects would not get deleted without the other table getting deleted first. More on deleting your own objects to come! 🛠️
So if you didn’t want some of the test data we created earlier to exist in your database schema, running something like this would delete them!
1
print('BEFORE DELETE: \n', session.query(RestaurantPhotoLabel).all())
2
3
for label in session.query(RestaurantPhotoLabel).all():
4
session.delete(label)
5
6
print('AFTER DELETE: \n', session.query(RestaurantPhotoLabel).all())
Copied!
With an output of the following, for confirmation:
1
BEFORE DELETE:
2
[<RestaurantPhotoLabel
3
id=1,
4
created_at='2021-11-23T19:13:02.546549',
5
updated_at='2021-11-23T19:13:02.546549',
6
image_url=None,
7
meal='breakfast',
8
ambiance='immaculate'>,
9
<RestaurantPhotoLabel
10
id=2,
11
created_at='2021-11-23T19:16:59.300798',
12
updated_at='2021-11-23T19:16:59.300798',
13
image_url=None,
14
meal='burrito',
15
ambiance='festive'>,
16
<RestaurantPhotoLabel
17
id=3,
18
created_at='2021-11-23T19:16:59.300798',
19
updated_at='2021-11-23T19:16:59.300798',
20
image_url=None,
21
meal='sushi',
22
ambiance='sophisticated'>,
23
<RestaurantPhotoLabel
24
id=4,
25
created_at='2021-11-23T19:16:59.300798',
26
updated_at='2021-11-23T19:16:59.300798',
27
image_url=None,
28
meal='pasta',
29
ambiance='casual'>]
30
AFTER DELETE:
31
[]
Copied!

Deleting multiple objects

Deleting everything inside a table but the table itself

Similar to SQL TRUNCATE:
1
Delete = context.classes(Delete)
2
session.query(Delete).delete()
Copied!
All that will remain is the table itself; all of its rows will be deleted. The auto-incremented ids will not reset. This will once again only work if the table to be deleted is not referenced in any other tables. If the table you’d like to delete does have nested relationships to other tables, keep reading ⬇️

Deleting nested tables

Deleting nested tables requires cascading deletes. This means tables must be deleted in the right order in order to cascade and get deleted properly. We provide a version of this for you in the **"**Data" page!
As always, think carefully before you delete your data!