SQLAlchemy内省具有继承的列类型 [英] SQLAlchemy introspect column type with inheritance

查看:135
本文介绍了SQLAlchemy内省具有继承的列类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑此代码(并使用SQLAlchemy 0.7.7):

Considering this code (and using SQLAlchemy 0.7.7):

class Document(Base):
    __tablename__ = 'document'
    __table_args__ = {
        'schema': 'app'
    }

    id = Column(types.Integer, primary_key=True)
    nom = Column(types.Unicode(256), nullable=False)
    date = Column(types.Date())

    type_document = Column(types.Enum('arrete', 'photographie',
        name='TYPES_DOCUMENT_ENUM'))
    __mapper_args__ = {'polymorphic_on': type_document}

class Arrete(Document):
    __tablename__ = 'arrete'
    __table_args__ = {
        'schema': 'app'
    }
    __mapper_args__ = {'polymorphic_identity': 'arrete'}

    id = Column(types.Integer, ForeignKey('app.document.id'), primary_key=True)
    numero_arrete = Column(types.Integer)
    date_arrete = Column(types.Date())

我可以轻松地内省 Arrete 类中定义的列的列类型:

I can easily introspect column type for column defined in Arrete class with:

Arrete.__table__.c['date_arrete'].type

但是如果我想通过 Arrete 类访问 Document 类中定义的列,则不起作用。 (KeyError,如果我尝试访问 c ['date'] )。

But this doesn’t work if I want to access, through the Arrete class, a column defined in Document class. (KeyError if I try to access c['date']).

有没有办法获取列类型,无论列是在最终类中还是在其父类中定义的?

Is there a way to get column type, regardless if the column is defined in the final class or in one of its parent?

推荐答案

ORM允许您在继承模式中定义类,这些模式对应于两个表的JOIN。这个结构是完整的服务,也可以用来找出基本的东西,比如列上的属性类型,非常直接:

The ORM has allowed you to define classes in an inheritance pattern that corresponds to a JOIN of two tables. This structure is full service, and can also be used to find out basic things like the types of attributes on columns, pretty much directly:

type = Arrete.date.property.columns[0].type

请注意,这基本上是与通过 __ bases __ 跋涉的方法相同,除了你让Python的普通类机制完成工作。

note that this is basically the same thing as the approach of trudging through __bases__, except you let Python's normal class mechanics do the work.

这篇关于SQLAlchemy内省具有继承的列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆