【发布时间】:2016-09-30 16:56:54
【问题描述】:
我正在开发一些集成 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)
我想获取链接到关系的列,以便我可以设置小部件是否有空白选项。
【问题讨论】:
标签: python sqlalchemy foreign-keys relationship