sqlalchemy获取同义词和关系的字段类型

时间:2017-12-02 00:45:42

标签: python orm sqlalchemy relationship synonym

我有一个SQL Alchemy ORM,我有常规列,同义词和关系。

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

当我使用会话从数据库中检索对象时,如何循环返回的对象并返回不具有同义词的常规字段,跳过具有同义词的字段,同义词本身并跳过关系?所以对于上面的内容,它应该只返回

    regular_field, field_synonym

并跳过

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

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您无法单独在实例上执行此操作,您需要查看类属性才能使其正常工作。如果您在类上查找具有相同名称的属性,则可以检查type或对类属性执行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

答案 1 :(得分:1)

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

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