我想知道如果知道一个对象,它是否是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?
答案 0 :(得分: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))
答案 1 :(得分:1)
对于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
对于calsses和UnmappedInstanceError
为实例)引发了特定错误,为什么不捕获它们而不是一般异常? ;)