2011-10-05 5 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()을 사용하고 예외를 catch 할 수 있습니다.
_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) 일반적인 예외가 아닌 캐치를 사용하지 않는 이유는 무엇입니까? ;)

관련 문제