SQLalchemy:将列映射到不同属性

2 投票
1 回答
1412 浏览
提问于 2025-04-16 11:52

我正在尝试使用sqlalchemy来存储一些模拟测量数据(时间和数值)。以下是相关的表格定义。如果有更合理的表格定义,我很想看看。

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

每个容器的时间都是独一无二的,下面的属性应该按照时间的顺序排列。

我希望能够读取和分配这些属性:

c = Container()

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

c.times  = times
c.values = values

但是我不知道该如何进行映射。我想如果可以的话,它的样子可能是这样的:

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

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

我该如何进行操作呢?这样的映射合理吗,还是我需要有不同的基础表结构?

1 个回答

2
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
})

这段代码是一个占位符,具体内容没有给出,所以我们无法看到它的实际内容。通常,这种代码块会包含一些编程代码或示例,帮助理解某个技术概念或解决方案。

如果你有具体的代码或问题,可以把它贴出来,我可以帮你解释得更清楚。

撰写回答