views:

41

answers:

1

When mapping an object using SQLAlchemy, is there a way to only map certain elements of a class to a database, or does it have to be a 1:1 mapping?

Example:

class User(object):
    def __init__(self, name, username, password, year_of_birth):
        self.name = name
        self.username = username
        self.password = password
        self.year_of_birth = year_of_birth

Say, for whatever reason, I only wish to map the name, username and password to the database and leave out the year_of_birth. Is that possible and will this create problems?

Edit - 25/03/2010

Additionally, say I want to map username and year_of_birth to a separate database. Will this database and the one above still be connected (via username)?

+2  A: 

Your mapper can specify what columns to map, you could even map a single table to multiple objects and multiple tables to a single object.

Here's the documentation for mapping a single object multiple times: http://www.sqlalchemy.org/docs/05/mappers.html#multiple-mappers-for-one-class

What you want is to configure what columns to map/not to map. This can be done by customizing the column properties. Docs: http://www.sqlalchemy.org/docs/05/mappers.html#customizing-column-properties

Example:

mapper(User, users_table, include_properties=['user_id', 'user_name'])

mapper(Address, addresses_table, exclude_properties=['street', 'city', 'state', 'zip'])
WoLpH
@WoLpH Many thanks!
Az