This article is part 3 of 11 in the series Python SQLAlchemy Tutorial

Last Updated: Sunday 25th May 2014
Update: A review of PonyORM has been added.

Overview of Python ORMs

As a wonderful language, Python has lots of ORM libraries besides SQLAlchemy. In this article, we are going to take a look at several popular alternative ORM libraries to better understand the big picture of the Python ORM landscape. By writing a script that reads and writes to a simple database with two tables, person and address, we will gain a better understanding about the pros and cons of each ORM library.

SQLObject

SQLObject is a Python ORM that maps objects between a SQL database and Python. It is becoming more popular in the programming community due to its similarity to Ruby on Rails' ActiveRecord pattern. The first version of SQLObject was released in October 2002. It is licensed under LGPL.

In SQLObject, database concepts are mapped into Python in a way that's very similar to SQLAlchemy, where tables are mapped as classes, rows as instances and columns as attributes. It also provides a Python-object-based query language that makes SQL more abstract, thus providing database agnosticity for applications.

The code above created two simple tables: person and address. To create or insert records into these two tables, we simply instantiate a person and an address like normal Python objects:

To get or retrieve the new records from the database, we use the magical q object attached to the Person and Address classes:

Storm

Storm is a Python ORM that maps objects between one or more databases and Python. It allows developers to construct complex queries across multiple database tables to support dynamic storage and retrieval of object information. It was developed in Python at Canonical Ltd., the company behind Ubuntu, for use in the Launchpad and Landscape applications and subsequently released in 2007 as free software. The project is released under the LGPL license and contributors are required to assign copyrights to Canonical.

Like SQLAlchemy and SQLObject, Storm also maps tables to classes, rows to instances and columns to attributes. Compared to the other two, Storm's table classes do not have to be subclasses of a special framework-specific superclass. In SQLAlchemy, every table class is a subclass of sqlalchemy.ext.declarative.declarative_bas. In SQLObject, every table class is a subclass of sqlobject.SQLObject.

Similar to SQLAlchemy, Storm's Store object acts as a surrogate to the backend database, where all the operations are cached in-memory and committed into the database once the method commit is called on the store. Each store holds its own set of mapped Python database objects, just like a SQLAlchemy session holding different sets of Python objects.

Specific versions of Storm can be downloaded from the download page. In this article, the example code is written in Storm version 0.20.

The code above created an in-memory sqlite database and a store to reference that database object. A Storm store is similar to a SQLAlchemy DBSession object, both of which manage the life cycles of instance objects attached to them. For example, the following code creates a person and an address, and inserts both records into the database by flushing the store.

To get or retrieve the inserted Person and Address objects, we call store.find() to find them:

Django's ORM

Django is a free and open source web application framework whose ORM is built tightly into the system. After its initial release, Django becomes more and more popular due to its straightforward design and easy-to-use web-ready features. It was released under the BSD license in July 2005. Since Django's ORM is built tightly into the web framework, it's not recommended, although possible, to use its ORM in a standalone non-Django Python application.

Django, one of the most popular Python web frameworks, has its own dedicated ORM. Compared to SQLAlchemy, Django's ORM is more geared towards direct SQL object manipulation where it exposes a plain and direct mapping between database tables and Python classes.

Since we cannot execute Django's code without creating a project first, we created a Django project 'demo' in the previous shell and entered the Django shell to test our ORM example.

The code above declared two Python classes, Person and Address, each of which maps to a database table. Before execute any database manipulation code, we need to create the tables in a local sqlite database.

To insert a person and an address into the database, we instantiate the corresponding objects and call the save() methods of those objects.

To get or retrieve the person and address objects, we use the magical objects attribute of the model classes to fetch the objects from the database.

peewee

peewee is a small, expressive ORM. Compared to other ORMs, peewee focuses on the principal of minimalism where the API is simple and the library is easy to use and understand.

To create a database model mapping, we implement a Person class and an Address class that map to the corresponding database tables.

To insert objects into the database, we instantiate the objects and call their save() methods. From object creation point of view, peewee is very similar to Django.

To get or retrieve the objects from the database, we select the objects from their respective classes.

PonyORM

PonyORM allows you to query the database using Python generators. These generators are translated into SQL and the results are automatically mapped into Python objects. Writing queries as Python generators makes it easy for programmers to quickly construct certain queries.

For example, let's use PonyORM to query the previous Person and Address models in a SQLite database.

Now we have a SQLite database in memory and two tables mapped to the db object, we can insert two objects into the database.

The call db.commit() actually commits the new objects p and a into the database. Now we can query the database using the generator syntax.

SQLAlchemy

SQLAlchemy is an open source SQL toolkit and ORM for the Python programming language released under the MIT license. It was released initially in February 2006 and written by Michael Bayer. It provides "a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language". It has adopted the data mapper pattern (like Hibernate in Java) rather than the active record pattern (like the one in Ruby on Rails).

SQLAlchemy's unit-of-work principal makes it essential to confine all the database manipulation code to a specific database session that controls the life cycles of every object in that session. Similar to other ORMs, we start by defining subclasses of declarative_base() in order to map tables to Python classes.

Before we write any database code, we need to create an database engine for our db session.

Once we have created a database engine, we can proceed to create a database session and create tables for all the database classes previously defined as Person and Address.

Now the session object becomes our unit-of-work constructor and all the subsequent database manipulation code and objects will be attached to a db session constructed by calling its __init__() method.

To get or retrieve the database objects, we call query() and filter() methods from the db session object.

Notice that so far we haven't committed any changes to the database yet so that the new person and address objects are not actually stored in the database yet. Calling s.commit() will actually commit the changes, i.e., inserting a new person and a new address, into the database.

Comparison Between Python ORMs

For each Python ORM presented in this article, we are going to list their pros and cons here:

SQLObject

Pros:

  1. Adopted the easy-to-understand ActiveRecord pattern
  2. A relatively small codebase

Cons:

  1. Naming of methods and classes follow Java's camelCase style
  2. Does not support database sessions to isolate unit of work

Storm

Pros:

  1. A clean and lightweight API leading to short learning curve and long-term maintainability
  2. Does not need special class constructors, nor imperative base classes

Cons:

  1. Forcing the programmer to write manual table-creation DDL statements instead of automatically deriving it from the model class
  2. Contributors of Storm have to give their contributions' copyrights to Canonical Ltd.

Django's ORM

Pros:

  1. Easy-to-use with a short learning curve
  2. Tightly integrated with Django to make it the de-factor standard when dealing with databases in Django

Cons:

  1. Does not handle complex queries very well; forcing the developer to go back to raw SQL
  2. Tightly integrated with Django; making it hard to use outside of a Django context

peewee

Pros:

  1. A Django-ish API; making it easy-to-use
  2. A lightweight implementation; making it easy to integrate with any web framework

Cons:

  1. Does not support automatic schema migrations
  2. Many-to-Many queries are not intuitive to write

SQLAlchemy

Pros:

  1. Enterprise-level APIs; making the code robust and adaptable
  2. Flexible design; making it painless to write complex queries

Cons:

  1. The Unit-of-work concept is not common
  2. A heavyweight API; leading to a long learning curve

PonyORM

Pros:

  1. A very convenient syntax for writing queries
  2. Automatic query optimization
  3. Simplified setup and usage

Cons:

  1. Not designed to process hundreds of thousands or millions of records simultaneously

Summary and Tips

Compared to other ORMs, SQLAlchemy stands out in its focus on the unit-of-work concept which is prevalent whenever you write SQLAlchemy code. The DBSession concept might be hard to understand and use correctly initially, but later you will appreciate the additional complexity which reduces accidental database commit-timing-related bugs to almost zero. Dealing with multiple databases in SQLAlchemy can be tricky since each DB session is confined to one database connection. However, this kind of limitation is actually a good thing since it forces you to think hard about the interaction between multiple databases and make it easier to debug database interaction code.

In the future articles, we are going to fully explore more advanced use cases of SQLAlchemy to truly grasp its immensely powerful APIs.

About The Author