2011-02-15 65 views
2

我正在嘗試使用sqlalchemy存儲一些模擬測量結果(時間和值)。這裏是相關的表格定義。如果有更明智的表格定義,我很樂意看到它。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
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 
}) 
+0

我知道屬性如何工作。問題的關鍵是我的當前(基於屬性)實現創建了很多不需要的對象(x-y對元組)。我認爲最好的解決方案實際上是使用一個blob,我只是沒有到處發佈我自己的答案。 – Mark 2011-04-02 16:00:23