O'Reilly logo

Essential SQLAlchemy, 2nd Edition by Rick Copeland, Jason Myers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required