Sqlalchemy获得同义词和关系的字段类型



我有一个sql炼金术,我有常规的列,同义词和关系。

class Table1(Base):
   regular_field = Column("RegularField", Integer)
   field = Column("TestField", String)
   field_synonym = synonym('field')
   relation_type = relationship("Table2", back_populates="Table1")

当我使用会话从DB中检索对象时,如何循环循环返回的对象并返回没有同义词的常规字段,跳过具有同义词的字段,同义词本身并跳过关系?因此,对于上述,它只能返回

    regular_field, field_synonym

和跳过

    field (since it has a synonym called field_synonym) 
    relation_type (which is a relationship).

我该怎么做?

您不能在实例上单独执行此操作,您需要查看该类属性的工作。如果您以相同名称查找类上的属性,则可以检查 type或在类 - attribute上检查isinstance

示例,给定您有一个table1实例

>>> table1.__class__.regular_field.__class__.__mro__
(sqlalchemy.orm.attributes.InstrumentedAttribute,
 sqlalchemy.orm.attributes.QueryableAttribute,
 sqlalchemy.orm.interfaces._MappedAttribute,
 sqlalchemy.orm.interfaces._InspectionAttr,
 sqlalchemy.orm.interfaces.PropComparator,
 sqlalchemy.sql.operators.ColumnOperators,
 sqlalchemy.sql.operators.Operators,
 object)

您可以检查这样的特定类

field = table1.__class__.field_synonym
if isinstance(field, sqlalchemy.orm.attributes.propertyProxy):
    # overwriting vars is bad style, just for illustration purposes!
    field = field.original_property

不知道同义词,但是这是一种检查对象属性是否是关系的方法(取自此答案):

table = Table1()
mapper_prop = type(table).relation_type.property
# Use getattr if you have a dynamic attribute name
# mapper_prop = getattr(type(obj), key).property
if isinstance(mapper_prop, RelationshipProperty):
    print('I am a relationship')

最新更新