2016-06-01 2 views
0

SQLalchemy, CRUD 항목을 통합하는 일부 wxpython 위젯을 만들고 있습니다. 관계에 의해 링크 된 테이블의 행을 나열하는 wx.ComboBox가 있습니다.SQLalchemy 관계에서 열 검색

class User(Base): 
    __tablename__ = 'user' 
    id = Column(Integer, primary_key=True) 
    name = Column(String(250), nullable=False) 

class Category(Base): 
    __tablename__ = 'category' 
    id = Column(Integer, primary_key=True) 
    name = Column(String(250), nullable=False) 

class Thing(Base): 
    __tablename__ = 'thing' 
    id = Column(Integer, primary_key=True) 
    description = Column(String(500), nullable=False) 
    user_id = Column(Integer, ForeignKey('user.id'), nullable=True) 
    user = relationship(User, foreign_keys = [user_id]) 
    category_id = Column(Integer, ForeignKey('category.id'), nullable=True) 
    category = relationship(Category, foreign_keys = [category_id]) 


class RelationBox(wx.ComboBox): 
    def __init__(self, parent, column): 
     wx.ComboBox.__init__(self, parent, style = wx.CB_READONLY) 
     self.nullable = True # column.nullable 
     self.linked_table = column.mapper.class_ 

     if self.nullable: 
      self.SetItems([""]) 

     self.options = session.query(self.linked_table) 

     session.commit() 

     for option in self.options: 
      self.Append(option.__repr__(), option) 

나는 코드를 단순화하고 일부만 추출하여 명확한 그림을 제공합니다. 나는 이런 식으로 구현했습니다

categories = ["user", "category"] 
category_sizer = wx.BoxSizer(wx.HORIZONTAL) 
self.column_widgets = {} 

for category in categories: 
    box = wx.BoxSizer(wx.VERTICAL) 
    box.Add(wx.StaticText(self, -1, category.capitalize()), 0, wx.ALIGN_CENTRE|wx.ALL, 5) 
    self.column_widgets[category] = RelationBox(self, getattr(Thing, category)) 
    box.Add(self.column_widgets[category], 1, wx.ALIGN_CENTRE|wx.ALIGN_TOP|wx.ALL, 2) 
    category_sizer.Add(box, 0, wx.ALIGN_CENTRE|wx.ALL, 5) 

가 나는 위젯이 빈 옵션이 아닌지 여부를 설정할 수 있도록 관계에 링크 된 열 싶어.

답변

1
당신은 .prop 속성을 검사하여 관계와 관련된 열을 얻을 수 있습니다

:

>>> Thing.category.prop.local_columns 
set([Column('category_id', Integer(), ForeignKey('category.id'), table=<thing>)]) 
>>> Thing.category.prop.remote_side 
set([Column('id', Integer(), table=<category>, primary_key=True, nullable=False)])) 

외래 키에 양측이 있으므로를, 당신은 어느 쪽 (local_columns 또는 remote_side) 당신이 선택 신중해야 .

는 다음을 수행, 인스턴스에서 값을 가져올 수 :

col, = Thing.category.prop.local_columns 
key = Thing.__mapper__.get_property_by_column(col).key 
getattr(thing, key) 
관련 문제