[英]Retrieving column from a SQLalchemy relationship
我正在研究一些集成SQLalchemy和CRUD的wxpython小部件。 我有一個wx.ComboBox,它列出了通過關系鏈接的表的行。
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)
我想獲取鏈接到該關系的列,以便我可以設置小部件是否具有空白選項。
您可以通過檢查.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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.