2011-10-05 30 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爲例)爲什麼不抓住它們而不是一般的異常? ;)

相關問題