SQLAlchemy建模属性操作和数据库访问

时间:2013-11-20 11:15:51

标签: python orm sqlalchemy getattr

假设我有SQLAlchemy ORM模型实例model及其属性attr_name的名称。

有没有办法确定getattr(model, attr_name)是否会查询数据库?我的意思是我需要一个函数getattr_does_emit_sql(model, attr_name)返回TrueFalse

1 个答案:

答案 0 :(得分:1)

解决了它。功能是

from sqlalchemy.orm.attributes import QueryableAttribute
def getattr_does_emit_sql(model, attr_name):
    return (attr_name not in model.__dict__ 
        and hasattr(type(model), attr_name
        and isinstance(getattr(type(model), attr_name), QueryableAttribute)
    )