Skip to content Skip to sidebar Skip to footer

Retrieving Column From A Sqlalchemy Relationship

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): __

Solution 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)

Post a Comment for "Retrieving Column From A Sqlalchemy Relationship"