Search code examples
pythonormsqlalchemygetattr

SQLAlchemy models attribute operations and DB access


Let's say that I have SQLAlchemy ORM model instance model and name of it's attribute attr_name.

Is there a way to determine whether getattr(model, attr_name) will or won't query the database? I mean that I need a function getattr_does_emit_sql(model, attr_name) returning True or False.


Solution

  • Solved it. The function is

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