Map only certain parts of the class to a database using SQLAlchemy?
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
)?
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'])
精彩评论