考虑这个简单的表定义(使用SQLAlchemy-0.5.6)
from sqlalchemy import *
db = create_engine('sqlite:///tutorial.db')
db.echo = False # Try changing this to True and see what happens
metadata = MetaData(db)
user = Table('user', metadata,
Column('user_id', Integer, primary_key=True),
Column('name', String(40)),
Column('age', Integer),
Column('password', String),
)
from sqlalchemy.ext.declarative import declarative_base
class User(declarative_base()):
__tablename__ = 'user'
user_id = Column('user_id', Integer, primary_key=True)
name = Column('name', String(40))
我想知道列名的最大长度是多少,例如来自用户表和用户(声明性类)
print user.name.length
print User.name.length
我已经尝试过(User.name.type.length)但它会抛出异常
Traceback (most recent call last):
File "del.py", line 25, in <module>
print User.name.type.length
File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.6-py2.5.egg/sqlalchemy/orm/attributes.py", line 135, in __getattr__
key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'type'
答案 0 :(得分:17)
User.name.property.columns[0].type.length
注意,SQLAlchemy支持复合属性,这就是columns
是列表的原因。它具有简单列属性的单个项目。
答案 1 :(得分:3)
这应该有效(在我的机器上测试):
print user.columns.name.type.length