检查对象是否为SQLAlchemy模型实例

8

我想知道如何判断一个对象是否是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?
2个回答

6
你可以使用 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))

谢谢Van。我的原始问题是关于对象实例而不是类。我需要将您的代码更改为object_mapper吗? - Ahmed
你可以随时获取一个实例的类;type(instance) - SingleNegationElimination
当然,你可以使用object_mapper。或者如上所示,只需获取类型。由你决定... - van

3

例如,有一个object_mapper(),那么:

from sqlalchemy.orm.base import object_mapper

def is_mapped(obj):
    try:
        object_mapper(obj)
    except UnmappedInstanceError:
        return False
    return True

完整的映射器工具文档在此处:http://docs.sqlalchemy.org/en/rel_1_0/orm/mapping_api.html
只是一个考虑:既然SQLAlchemy引发了特定的错误(UnmappedClassError用于类和UnmappedInstanceError用于实例),为什么不捕获它们而不是通用异常? ;)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接