【问题标题】:Retrieving column from a SQLalchemy relationship从 SQLalchemy 关系中检索列
【发布时间】: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


    【解决方案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_columnsremote_side)。

    要从实例中获取值,请执行以下操作:

    col, = Thing.category.prop.local_columns
    key = Thing.__mapper__.get_property_by_column(col).key
    getattr(thing, key)
    

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2023-01-04
      相关资源
      最近更新 更多