如何确定对象是否是SQLAlchemy映射的对象?

时间:2015-06-05 03:05:25

标签: python sqlalchemy

如何确定对象是否是SQLAlchemy映射对象? 这意味着它是否来自sqlalchemy.ext.declarative.declarative_base()。 使用isinstance()在我的测试中不起作用。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sqlalchemy
import sqlalchemy.ext.declarative

Base = sqlalchemy.ext.declarative.declarative_base()

class Model(Base):
    __tablename__ = 'Table'
    _oid = sqlalchemy.Column('oid', sqlalchemy.Integer, primary_key=True)


model = Model()

# of course this is False
print ( Base == sqlalchemy.ext.declarative.declarative_base() )

# this can not work even
print( isinstance( model,
                   sqlalchemy.ext.declarative.declarative_base() ) )

# but 'Base' is unknown at this point
# I need a generalized way to find out if a given instance is mapped
# by SQLAlchemy

1 个答案:

答案 0 :(得分:0)

insp = sqlalchemy.inspection.inspect(model)

当它不是SQLAlchemy对象时,这会引发sqlalchemy.exc.NoInspectionAvailable

有关详细信息,请参阅http://docs.sqlalchemy.org/en/rel_1_0/core/inspection.html#sqlalchemy.inspection.inspect