A.3. Data Mapper and Active RecordAs discussed initially in Chapter 8, "RSS, Cookies, and Dynamic Views in WhatWhat Status," SQLObject follows the Active Record design pattern. In short, this pattern says that each table in your database is represented by a Python class. Instances of those objects directly represent rows in the database table. The Data Mapper pattern adds an extra layer. There are classes that represent the tables in the database, but there are also objects that separately map from database tables to your classes. The Data Mapper pattern has some advantages over Active Record:
The drawback to the Data Mapper pattern is that it requires more setup. Instead of setting up one class, you now have two to worry about. It turns out, though, that the Data Mapper pattern is a superset of Active Record. There is an extension included with SQLAlchemy called ActiveMapper. When your Python class subclasses ActiveMapper, ActiveMapper creates Table and Mapper objects behind the scenes, giving you the same ease-of-use that you get from an Active Record-based library such as SQLObject. Choosing to use ActiveMapper at the beginning of the project does not mean you lose any of SQLAlchemy's power. You can still access a class's Table object by looking up the table class property: class Plate(ActiveMapper): class mapping: size = column(Integer) print type(Plate.table) <class 'sqlalchemy.schema.Table'> |