SQLAlchemy introspection

本秂侑毒 提交于 2019-12-04 12:29:40

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!