2017-06-14 59 views
1

我寫的屬性變化的歷史sqlalchemy模型。屬性列表對於歷史很重要,我保留在類屬性history_attributes中。爲什麼sqlalchemy.Column實例的屬性'name'消失?

from sqlalchemy import Integer, Column, String 
from sqlalchemy.ext.declarative import declarative_base 
Base = declarative_base() 
class HistoryAttribute: 
    def __init__(self, descriptor, display_name, use_message=False): 
     self.name = descriptor.name 
     self.display_name = display_name 
     self.use_message = use_message 
class User(Base): 
    __tablename__ = 'user' 
    id = Column(Integer, primary_key=True) 
    first_name = Column(String(100)) 
    email = Column(String(100)) 
    history_attributes = (
     HistoryAttribute(descriptor=first_name, display_name='User name'), 
     email 
    ) 

print(User.history_attributes[0].name) 
>>> None 
print(User.history_attributes[1].name) 
>>> email 

爲什麼Column實例的屬性"name"消失,如果我通過一個其他類的構造函數?當然,我可以寫first_name = Column('first_name', String(100)和代碼將正常工作, 但我不希望添加Column.name明確。我使用namedtuple,然後我傳遞給HistoryAttribute類的構造避免了問題,但它是非常相似的柺杖。

回答

3

這並不是說name屬性消失,但它尚未初始化。看看first_name值傳遞給HistoryAttributeColumn(String(100));它不包含字符串first_name的任何提及。在定義類之後,SQLAlchemy將在稍後填寫名稱。

1

如前所述,問題在於first_name.name是在構造類時設置的。 SQLAlchemy的確實有推遲屬性定義直至配置時間的機制。嘗試類似 類用戶(基本): #...... @ sqlalchemy.ext.declarative.api.declared_attr 高清history_attributes(個體經營): 回報(HistoryAttribute(self.first_name#...))

這將推遲history_attributes的構造,直到填充列名爲止

+0

declared_attr不適合,因爲我想從類中獲取history_attributes,但這引發了使用classmethod的想法,該方法返回所需的元組HistoryAttribute實例 – Stright

+0

我很困惑declare_attr是如何得到的。配置完成後,我確信訪問該類會爲您提供實例。也就是說,在課堂建設過程中,我相當肯定元類將用正確的東西替換declared_attr。在你的情況下,classmethod會起作用,但除非你記憶,否則會稍微短一些。 –

+0

也許我誤解了你,但declared_attr給了我相同的結果( [代碼示例](https://codeshare.io/5RB0dB) – Stright

相關問題