3

我想要做的是从 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、出生日期,确定它们的限制(例如 title 是字符串,最大长度是 512 或birth_date 是 datetime 等)

谢谢

4

1 回答 1

7

如果您正在使用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>]

否则,请参阅文档的访问表和列部分。同样,从文档中提取代码:

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
于 2012-07-04T15:13:03.687 回答