gpt4 book ai didi

python - SQLAlchemy 自省(introspection)

转载 作者:太空宇宙 更新时间:2023-11-03 13:49:56 26 4
gpt4 key购买 nike

我想做的是从 SqlAlchemy 实体定义中获取所有 Column() 的内容,确定它们的类型和约束,以便能够预验证、转换数据并向用户显示自定义表单。

我如何反省它?

例子:

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,title,birth date,判断他们的限制(比如title是string,最大长度是512或者birth_date是datetime等)

谢谢

最佳答案

如果您使用的是 sqlalchemy 0.8,那么您应该查看新功能 New Class Inspection System .文档中的示例代码摘录:

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

否则,请参阅 Accessing Tables and Columns文档的一部分。同样,从文档中提取代码:

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

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com