now I have a real question based on example 1 above.
i.e. wanting an object with the following attributes:
customer.o_cutype
customer.id
customer.type (converted from cutype through mapping function)
from
create table old_customer (cunr number, cutype char(1));
The following works:
PREFIX = 'o_'
class Customer(Base):
__tablename__ = 'old_customer'
__table_args__ = {'autoload':True}
__mapper_args__ = {'column_prefix' : PREFIX}
id = Column('cunr', Integer, primary_key=True)
def _get_type(self):
def mapping(x):
return ord(x)
return mapping(self.o_cutype)
type = synonym('o_cutype', descriptor=property(_get_type))
Session = sessionmaker()
session = Session()
customer = session.query(Customer).filter_by(id=1).one()
print customer.id
print 'type mapping %s -> %d' % (customer.o_cutype, customer.type)
Then when I want to make the mapping / transformation more generic..
e.g. by just supplying a list like:
__transforms__ = [ ('cutype', 'type', lambda x:ord(x)) ]
I came up with the following which seems to work:
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker, synonym
from sqlalchemy.ext.declarative import declarative_base,
DeclarativeMeta
engine=create_engine('oracle://gw_val:[EMAIL PROTECTED]')
Base = declarative_base(engine=engine)
PREFIX = 'o_'
def make_getter(oldname, fn):
def getter(self):
return fn(getattr(self, PREFIX + oldname))
return getter
class MyMeta(DeclarativeMeta):
def __new__(meta, classname, bases, classdict):
for oldname, newname, fn in classdict['__transforms__']:
getter = make_getter(oldname, fn)
classdict['_get_' + newname] = getter
classdict[newname] = synonym(PREFIX + oldname,
descriptor=property(getter))
return type.__new__(meta, classname, bases, classdict)
class Customer(Base):
__metaclass__ = MyMeta
__transforms__ = [ ('cutype', 'type', lambda x:ord(x)) ]
__tablename__ = 'old_customer'
__table_args__ = {'autoload':True}
__mapper_args__ = {'column_prefix' : PREFIX}
id = Column('cunr', Integer, primary_key=True)
#def _get_type(self):
#def mapping(x):
#return ord(x)
#return mapping(self.o_cutype)
#type = synonym('o_cutype', descriptor=property(_get_type))
Session = sessionmaker()
session = Session()
customer = session.query(Customer).filter_by(id=1).one()
print customer.id
print 'type mapping %s -> %d' % (customer.o_cutype, customer.type)
Question is - Is this recommended, am I overcomplicating things with
the metaclass?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"sqlalchemy" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---