简体   繁体   中英

SQLalchemy: Mapping columns into different properties

I am trying to store some simulation measurements (times and values) using sqlalchemy. Here are the relevant table definitions. If there is a more sensible table definition, I'd love to see it.

from sqlalchemy import create_engine, schema, orm

engine = create_engine('sqlite:///:memory:', echo=True)
metadata = schema.MetaData(bind=engine)

container_table = schema.Table('containers', metadata,
        schema.Column('id', schema.types.Integer, primary_key=True))

measurement_table = schema.Table('measurements', metadata,
        schema.Column('id', schema.types.Integer, primary_key=True),
        schema.Column('container_id', schema.types.Integer,
                      schema.ForeignKey('containers.id')),
        schema.Column('time',  schema.types.Float),
        schema.Column('value', schema.types.Float))

metadata.create_all()

The times will be unique for each container, and the below properties should be ordered by time.

I would like to be able to both read and assign these properties:

c = Container()

times  = range(10)
values = [t**2 for t in times]

c.times  = times
c.values = values

But I don't know how to do the mapping. I assume that if it's possible, it will look something like this:

class Container(object):
    times  = some_sort_of_proxy()
    values = some_sort_of_proxy()

orm.mapper(Container, container_table, properties={
        # Magic
        })

How do I go about doing this? Is this a reasonable mapping, or do I need to have a different underlying table structure?

class EmailAddress(object):

    @property
    def email(self):
        return self._email

    @email.setter
    def email(self, email):
        self._email = email

mapper(EmailAddress, addresses_table, properties={
    '_email': addresses_table.c.email
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM