python - ORM 类/对象的 SQLAlchemy 自省(introspection)

标签 python sqlalchemy introspection

我正在寻找一种方法来检查 SQLAlchemy ORM 类/实体以确定实体属性的类型和其他约束(如最大长度)。

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

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 的字符串,并且可以为 null。并且“created_timestamp”字段是 DateTime 且不可为 null。

最佳答案

类似于:

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

编辑:

即将推出的 0.8 版本有一个 New Class Inspection System :

New Class Inspection System

Status: completed, needs docs

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.

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 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:

(点击链接了解更多信息)

关于python - ORM 类/对象的 SQLAlchemy 自省(introspection),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2784986/

相关文章:

postgresql - Postgres : unique on array and varchar column

python - Python中的动态类实例化

python - 获取Python中的所有对象属性?

python - 关于图形工具中嵌套 block 模型的基本问题

python - utf-8中字符的编码问题

python - sqlalchemy 不强制执行外键约束

python - 编写 elisp 程序来自动自省(introspection) Python 对象

python - 使用 'for' 循环中的变量删除 Python 中的额外空格

Python HTML 最小化器

mysql - 跟踪关系数据库表中的随机列数据更改