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:

session.delete(photo)

To delete by id or another field, do the following:

session.query(RestaurantPhotoLabel).filter_by(id=6).delete()

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!

print('BEFORE DELETE: \n', session.query(RestaurantPhotoLabel).all())

for label in session.query(RestaurantPhotoLabel).all():
    session.delete(label)

print('AFTER DELETE: \n', session.query(RestaurantPhotoLabel).all())

With an output of the following, for confirmation:

BEFORE DELETE: 
 [<RestaurantPhotoLabel
    id=1,
    created_at='2021-11-23T19:13:02.546549',
    updated_at='2021-11-23T19:13:02.546549',
    image_url=None,
    meal='breakfast',
    ambiance='immaculate'>, 
<RestaurantPhotoLabel
    id=2,
    created_at='2021-11-23T19:16:59.300798',
    updated_at='2021-11-23T19:16:59.300798',
    image_url=None,
    meal='burrito',
    ambiance='festive'>, 
<RestaurantPhotoLabel
    id=3,
    created_at='2021-11-23T19:16:59.300798',
    updated_at='2021-11-23T19:16:59.300798',
    image_url=None,
    meal='sushi',
    ambiance='sophisticated'>, 
<RestaurantPhotoLabel
    id=4,
    created_at='2021-11-23T19:16:59.300798',
    updated_at='2021-11-23T19:16:59.300798',
    image_url=None,
    meal='pasta',
    ambiance='casual'>]
AFTER DELETE: 
 []

Deleting multiple objects

Deleting everything inside a table but the table itself

Similar to SQL TRUNCATE:

Delete = context.classes(Delete)
session.query(Delete).delete()

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!

Learn more about deleting objects using SQLAlchemy.

Last updated