问题
I'm working on some wxpython widgets that integrate SQLalchemy, CRUD stuff. I've got a wx.ComboBox that lists the rows of a table linked by a relationship.
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)
I've simplified the code and only extracted some of it to hopefully give you a clearer picture. I've implemented it like this:
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)
I want to get the Column that is linked to the relationship so I can set whether the widget has a blank option or not.
回答1:
You can get the column associated with a relationship by inspecting the .prop
attribute:
>>> 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)]))
Because there are two sides to a foreign key, you need to be careful which one (local_columns
or remote_side
) you choose.
To then fetch the value from an instance, do the following:
col, = Thing.category.prop.local_columns
key = Thing.__mapper__.get_property_by_column(col).key
getattr(thing, key)
来源:https://stackoverflow.com/questions/37566707/retrieving-column-from-a-sqlalchemy-relationship