Querying objects

Query objects in your Baseten Postgres tables from Code blocks.

Let's say that we want to query for RestaurantPhotoLabel(s) in a Code block:

  • session.query(RestaurantPhotoLabel).first() returns the first RestaurantPhotoLabel object

  • session.query(RestaurantPhotoLabel).all() returns a list of all RestaurantPhotoLabel objects

  • session.query(RestaurantPhotoLabel).order_by(RestaurantPhotoLabel.id).all() returns a list of all RestaurantPhotoLabel objects, ordered in ascending order by id

    • For descending order do order_by(RestaurantPhotoLabel.id.desc())

  • session.query(RestaurantPhotoLabel).count() returns a number that represents the count of RestaurantPhotoLabel objects

  • session.query(RestaurantPhotoLabel).filter_by(id=2).first() will find a specific object (the one with id=2), and return exactly one object

  • session.query(RestaurantPhotoLabel).filter(RestaurantPhotoLabel.ambiance=='casual').all() will find all objects where ambiance is casual

🔗 Queries are chainable. A lot of the query functions like the ones described above (order_by, filter, etc) return queries as well.

As you may have noticed, any query command on RestaurantPhotoLabel must take the form: session.query(RestaurantPhotoLabel).<modifier_or_clause_methods>()

Here we are querying for all RestaurantPhotoLabel objects ordered by id, and then printing out each object’s information.

for label in session.query(RestaurantPhotoLabel).order_by(RestaurantPhotoLabel.id).all():
    print(label.id, label.meal, label.ambiance)

...and the output looks something like this! Some places with pretty tasty food and good vibes 😋

1 breakfast immaculate
2 burrito festive
3 sushi sophisticated
4 pasta casual

Learn more about querying objects using SQLAlchemy.

Last updated