2011-10-05 6 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を提起しているので、カルサスとUnmappedInstanceError)なぜ一般的な例外ではなく、それらをキャッチしないのですか? ;)

関連する問題