2011-10-05 27 views
6

我想知道如何知道给定对象是否是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? 
+0

提供更多信息! – shahjapan

回答

4

您可以使用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)) 
+0

谢谢。我最初的问题是关于对象实例而不是类。我是否将代码更改为object_mapper? – Ahmed

+0

您可以随时获得实例的类; 'type(instance)' – SingleNegationElimination

+0

当然,你可以使用object_mapper。或者如上所述,只需获取类型即可。由你决定... – van

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为例)为什么不抓住它们而不是一般的异常? ;)

相关问题