SQLAlchemy内省 [英] SQLAlchemy introspection
问题描述
我想做的是从SqlAlchemy实体定义中获取Column()的所有内容,确定它们的类型和约束,以便能够进行预验证,转换数据并向用户显示自定义表单.
What I am trying to do is to get from SqlAlchemy entity definition all it's Column()'s, determine their types and constraints, to be able to pre-validate, convert data and display custom forms to user.
如何进行内省?
示例:
class Person(Base):
'''
Represents Person
'''
__tablename__ = 'person'
# Columns
id = Column(String(8), primary_key=True, default=uid_gen)
title = Column(String(512), nullable=False)
birth_date = Column(DateTime, nullable=False)
我想获取此ID,标题,出生日期,确定其限制(例如标题为字符串,最大长度为512或birth_date为datetime等)
I want to get this id, title, birth date, determine their restrictions (such as title is string and max length is 512 or birth_date is datetime etc)
谢谢
推荐答案
If you are using sqlalchemy 0.8
, then you should check out the new feature New Class Inspection System. Sample code extract from the documentation:
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
name_syn = synonym(name)
addresses = relationship(Address)
# universal entry point is inspect()
>>> b = inspect(User)
# column collection
>>> b.columns
[<id column>, <name column>]
否则,请参见访问表和列文档的一部分.同样,从文档中提取代码:
Otherwise, see Accessing Tables and Columns part of the documentation. Again, code extract from the docu:
employees = Table(...)
# or if using declarative
#employees = Employee.__table__
# or just
employees.c.employee_id
# via string
employees.c['employee_id']
# iterate through all columns
for c in employees.c:
print c
# access a column's name, type, nullable, primary key, foreign key
employees.c.employee_id.name
employees.c.employee_id.type
employees.c.employee_id.nullable
employees.c.employee_id.primary_key
employees.c.employee_dept.foreign_keys
这篇关于SQLAlchemy内省的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!