检查对象是否是sqlalchemy模型实例

Ahm*_*med 7 sqlalchemy

我想知道如果知道一个对象,它是否是sqlalchemy映射模型的一个实例.

通常,我会使用isinstance(obj,DeclarativeBase).但是,在这种情况下,我没有使用可用的DeclarativeBase类(因为它在依赖项目中).

我想知道在这种情况下最佳做法是什么.

class Person(DeclarativeBase):
      __tablename__ = "Persons"

p = Person()

print isinstance(p, DeclarativeBase)
#prints True

#However in my scenario, I do not have the DeclarativeBase available
#since the DeclarativeBase will be constructed in the depending web app
#while my code will act as a library that will be imported into the web app
#what are my alternatives?
Run Code Online (Sandbox Code Playgroud)

van*_*van 5

您可以使用class_mapper()并捕获异常.
或者你可以使用_is_mapped_class,但理想情况下你不应该使用,因为它不是一个公共方法.

from sqlalchemy.orm.util import class_mapper
def _is_sa_mapped(cls):
    try:
        class_mapper(cls)
        return True
    except:
        return False
print _is_sa_mapped(MyClass)

# @note: use this at your own risk as might be removed/renamed in the future
from sqlalchemy.orm.util import _is_mapped_class
print bool(_is_mapped_class(MyClass))
Run Code Online (Sandbox Code Playgroud)