Chapter 6. Defining Schema with SQLAlchemy ORM

You define schema slightly different when using the SQLAlchemy ORM because it is focused around user-defined data objects instead of the schema of the underlying database. In SQLAlchemy Core, we created a metadata container and then declared a Table object associated with that metadata. In SQLAlchemy ORM, we are going to define a class that inherits from a special base class called the declarative_base. The declarative_base combines a metadata container and a mapper that maps our class to a database table. It also maps instances of the class to records in that table if they have been saved. Let’s dig into defining tables in this manner.

Defining Tables via ORM Classes

A proper class for use with the ORM must do four things:

  • Inherit from the declarative_base object.

  • Contain __tablename__, which is the table name to be used in the database.

  • Contain one or more attributes that are Column objects.

  • Ensure one or more attributes make up a primary key.

We need to examine the last two attribute-related requirements a bit closer. First, defining columns in an ORM class is very similar to defining columns in a Table object, which we discussed in Chapter 2; however, there is one very important difference. When defining columns in an ORM class, we don’t have to supply the column name as the first argument to the Column constructor. Instead, the column name will be set to the name of the class attribute to which it is assigned. Everything ...

Get Essential SQLAlchemy, 2nd Edition 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.