代码之家  ›  专栏  ›  技术社区  ›  Anurag Uniyal

如何获取字符串列的sqlAlchemy长度

  •  13
  • Anurag Uniyal  · 技术社区  · 15 年前

    考虑这个简单的表定义(使用sqlacalchemy-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'
    
    2 回复  |  直到 12 年前
        1
  •  17
  •   Denis Otkidach    15 年前
    User.name.property.columns[0].type.length
    

    注意,sqlacalchemy支持复合属性,这就是为什么 columns 是一个列表。对于简单的列属性,它有单个项。

        2
  •  3
  •   Pierre Bourdon    15 年前

    这应该可以工作(在我的机器上测试):

    print user.columns.name.type.length