SQLAlchemy - how to map against a read-only (or calculated) property

Posted by Jeff Peck on Stack Overflow See other posts from Stack Overflow or by Jeff Peck
Published on 2010-06-11T05:29:43Z Indexed on 2010/06/11 5:32 UTC
Read the original article Hit count: 295

Filed under:
|
|
|

I'm trying to figure out how to map against a simple read-only property and have that property fire when I save to the database.

A contrived example should make this more clear. First, a simple table:

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),
    )

What I want to do is set up a class with a read-only property that will insert into the calculated_value column for me when I call session.commit()...

import datetime
def 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

According to the sqlalchemy docs, I think I am supposed to map this like so:

mapper(Foo, foo_table, properties = {
    'calculated_value' : synonym('_calculated_value', map_column=True)
    })

The problem with this is that _calculated_value is None until you access the calculated_value property. It appears that SQLAlchemy is not calling the property on insertion into the database, so I'm getting a None value instead. What is the correct way to map this so that the result of the "calculated_value" property is inserted into the foo table's "calculated_value" column?

© Stack Overflow or respective owner

Related posts about python

Related posts about property