Chapter 7. Querying and Updating at the ORM Level

This chapter introduces the SQLAlchemy Session object. You will learn how to use the Session to perform queries and updates of mapped classes, as well as how to customize the Session class and create a “contextual” session that simplifies session management.

The SQLAlchemy ORM Session Object

SQLAlchemy manages all querying and updating of objects in the ORM with Session objects. The Session is responsible for implementing the unit of work pattern of synchronization between in-memory objects and database tables. Sessions also provide a rich interface for querying the database based on object attributes rather than the underlying SQL database structure.

Creating a Session

The first step in creating a session is to obtain a Session object from SQLAlchemy. One way to do this is to directly instantiate the sqlalchemy.orm.session.Session class. However, this constructor for the SQLAlchemy-provided Session has a number of keyword arguments, making instantiating Sessions in this manner verbose and tedious. In order to alleviate this burden, SQLAlchemy provides the sessionmaker() function, which returns a subclass of orm.session.Session with default arguments set for its constructor.

Once you have this customized Session class, you can instantiate it as many times as necessary in your application without needing to retype the keyword arguments (which in many applications will not change between Session instantiations). If you wish to override ...

Get Essential SQLAlchemy now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.