Creating objects

Create objects within your Baseten Postgres tables.

Adding a single object

Let's say that we want to create a new RestaurantPhotoLabel in a Code block with a block_input of:

{
     "meal": "breakfast",
     "ambiance": "immaculate"
}

Creating a RestaurantPhotoLabel inside your Code block will look like this:

photo = RestaurantPhotoLabel(
    meal=block_input['meal'],
    ambiance=block_input['ambiance']
)
session.add(photo)

(we’ll be referencing this photo created a couple more times in this documentation)

session.add(...) is necessary, otherwise you’ve only created an object in memory and never committed it to the database.

Adding multiple objects

If you want to create more than one object without having to run subsequent session.add(...) commands, look no further!

session.add_all([
    RestaurantPhotoLabel(meal='burrito', ambiance='festive'),
    RestaurantPhotoLabel(meal='sushi', ambiance='sophisticated'),
    RestaurantPhotoLabel(meal='pasta', ambiance='casual')
])

Putting this in context (pun intended), running:

print(session.query(RestaurantPhotoLabel).all()) 

returns the following:

[<RestaurantPhotoLabel
    id=1,
    ...
    meal='breakfast',
    ambiance='immaculate'>, 
<RestaurantPhotoLabel
    id=2,
    ...
    meal='burrito',
    ambiance='festive'>,
<RestaurantPhotoLabel
    id=3,
    ...
    meal='sushi',
    ambiance='sophisticated'>, 
<RestaurantPhotoLabel
    id=4,
    ...
    image_url=None,
    meal='pasta',
    ambiance='casual'>]

Learn more about adding and updating objects using SQLAlchemy.

Last updated