ORM类/对象的SQLAlchemy自省 [英] SQLAlchemy introspection of ORM classes/objects

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

问题描述

我正在寻找一种反思SQLAlchemy ORM类/实体的方法,以确定实体属性的类型和其他约束(例如最大长度).

I am looking for a way to introspect SQLAlchemy ORM classes/entities to determine the types and other constraints (like maximum lengths) of an entity's properties.

例如,如果我有一个声明式类:

For example, if I have a declarative class:

class User(Base):
    __tablename__ = "USER_TABLE"

    id = sa.Column(sa.types.Integer, primary_key=True)
    fullname = sa.Column(sa.types.String(100))
    username = sa.Column(sa.types.String(20), nullable=False)
    password = sa.Column(sa.types.String(20), nullable=False)
    created_timestamp = sa.Column(sa.types.DateTime, nullable=False)

我希望能够发现'fullname'字段应该是最大长度为100的字符串,并且可以为空.并且created_timestamp'字段是DateTime,不能为空.

I would want to be able to find out that the 'fullname' field should be a String with a maximum length of 100, and is nullable. And the 'created_timestamp' field is a DateTime and is not nullable.

推荐答案

类似的东西:

table = User.__table__
field = table.c["fullname"]
print "Type", field.type
print "Length", field.type.length
print "Nullable", field.nullable

即将发布的0.8版本具有新类检查系统:

The upcoming 0.8 version has a New Class Inspection System:

新班级检查系统

New Class Inspection System

状态:已完成,需要文档

Status: completed, needs docs

许多SQLAlchemy用户正在编写需要该功能的系统 检查映射类的属性,包括能够 到达主键列,对象关系,普通 属性等,通常用于构建 数据编组系统,例如JSON/XML转换方案和 课程表格库丰富.

Lots of SQLAlchemy users are writing systems that require the ability to inspect the attributes of a mapped class, including being able to get at the primary key columns, object relationships, plain attributes, and so forth, typically for the purpose of building data-marshalling systems, like JSON/XML conversion schemes and of course form libraries galore.

最初,表"和列"模型是原始检查 要点,这些要有完善的文档系统.而SQLAlchemy ORM 型号也是完全自省的,这从来都不是完全自省的 稳定且受支持的功能,并且用户往往不清楚 想知道如何获取这些信息.

Originally, the Table and Column model were the original inspection points, which have a well-documented system. While SQLAlchemy ORM models are also fully introspectable, this has never been a fully stable and supported feature, and users tended to not have a clear idea how to get at this information.

0.8计划为此目的产生一个一致,稳定且有完整文档的API,这将提供一个检查系统, 适用于类,实例以及可能的其他事物.尽管 该系统的许多元素已经可用,计划是 锁定API,包括可从此类访问器访问的各种访问器 对象,如Mapper,InstanceState和MapperProperty:

0.8 has a plan to produce a consistent, stable and fully documented API for this purpose, which would provide an inspection system that works on classes, instances, and possibly other things as well. While many elements of this system are already available, the plan is to lock down the API including various accessors available from such objects as Mapper, InstanceState, and MapperProperty:

(点击链接获取更多信息)

(follow the link for more info)

这篇关于ORM类/对象的SQLAlchemy自省的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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