On Jun 11, 10:13 am, Michael Bayer <mike...@zzzcomputing.com> wrote: > On Jun 11, 2010, at 5:16 AM, jpeck wrote: > > > > > > > I am trying to map to a simple read only property. According to the > > docs, I *think* I am supposed to use synonym. The problem is that I am > > getting a None value for the mapped descriptor's column. > > > For example: > > > import datetime > > from sqlalchemy import Column, Table, Integer, String, MetaData, > > create_engine > > from sqlalchemy.orm import mapper, sessionmaker, synonym > > > meta = MetaData() > > foo_table = Table('foo', meta, > > Column('id', String(3), primary_key=True), > > Column('description', String(64), nullable=False), > > Column('calculated_value', Integer, nullable=False), > > ) > > > class Foo(object): > > def __init__(self, id, description): > > self.id = id > > self.description = description > > > �...@property > > def calculated_value(self): > > self._calculated_value = datetime.datetime.now().second + 10 > > return self._calculated_value > > > mapper(Foo, foo_table, > > properties = { > > 'calculated_value' : synonym('_calculated_value', > > map_column=True) > > } > > ) > > wouldn't this be simpler ? > > class Foo(object): > def __init__(self, id, description): > self.id = id > self.description = description > self.calculated_value = datetime.now().second + 10 > > mapper(Foo, foo_table) > > want it read only ? > > class Foo(object): > def __init__(self, id, description): > self.id = id > self.description = description > self._calculated_value = datetime.now().second + 10 > > @property > def calculated_value(self): > return self._calculated_value > > mapper(Foo, foo_table, > properties={'_calculated_value':foo_table.c.calculated_value}) > > another option is to stick "datetime.now().second + 10" into theTable > directly as a "default" for the Column. If it were still empty at flush > time, it would get persisted at that point.
Michael - thanks for the response. My original post was just a contrived example, and I should probably have included something closer to what I was actually doing. In my production code I was using the read only descriptor to iterate over a list of objects to calculate a value. I need the property to calculate the value on the fly in case something gets added/deleted from the list of objects. The issue I had was that I needed the property to fire just before insertion into the database to update the value referenced by synonym. I ended up using MapperExtension to access the property before the insertion occurred... -- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To post to this group, send email to sqlalch...@googlegroups.com. To unsubscribe from this group, send email to sqlalchemy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.