2017-07-27 64 views
0

自定義類型我有一個非常簡單的ChoiceString自定義列/數據類型:如何「考察」中的SQLAlchemy

class ChoiceString(types.TypeDecorator): 

    impl = types.String 

    def __init__(self, choices, **kw): 
     self.choices = dict(choices) 
     super(ChoiceString, self).__init__(**kw) 

    def process_bind_param(self, value, dialect): 
     return [k for k, v in self.choices.iteritems() if v == value][0] 

    def process_result_value(self, value, dialect): 
     return self.choices[value] 

而且我用的是mapper遍歷表列:

from sqlalchemy.inspection import inspect 

mapper = inspect(SomeTableClass) 

for col in mapper.columns: 
    print col 
    # how to check the choice values? 
    print dir(mapper.columns[col]) # does not show the 'choices' attribute 
    print dir(inspect(mapper.columns[col])) # does not show the 'choices' attribute 
    print mapper.columns[col].choices # error 

但我似乎無法訪問自定義類型的自定義屬性choices。我也嘗試過直接「檢查」列而不是班級,但那也行不通。

那麼我們如何在檢查時訪問sqlalchemy中的自定義類型的自定義屬性?

回答

1

您正在檢查Column對象,而不是其類型。訪問類型通過type屬性Column對象:

In [9]: class SomeTableClass(Base): 
    ...:  __tablename__ = 'sometableclass' 
    ...:  id = Column(Integer, primary_key=True) 
    ...:  choices = Column(ChoiceString({ 'asdf': 'qwer'})) 
    ...:  

In [10]: mapper = inspect(SomeTableClass) 

In [12]: mapper.columns['choices'] 
Out[12]: Column('choices', ChoiceString(), table=<sometableclass>) 

In [13]: mapper.columns['choices'].type.choices 
Out[13]: {'asdf': 'qwer'} 
+0

啊,你說得對! –

+2

作爲缺點,我無法找到該屬性的文檔,所以它可能是一個「實現細節」。謹慎使用。 –