views:

334

answers:

2

e.g. consider this simple table definition (using 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))

I want to know what is the max length of column name e.g. from user table and from User (declarative class)

print user.name.length
print User.name.length

I have tried (User.name.type.length) but it throws exception

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'
+1  A: 

This should work (tested on my machine) :

print user.columns.name.type.length
Pierre Bourdon
+ thanks it works, but my usecase was bit different , I am basically using declarative_base to define a User class, how can i get length from class, please see modified question
Anurag Uniyal
`print User.name.type.length` does not work ?
Pierre Bourdon
yes it throws exception 'AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'type'' update Question
Anurag Uniyal
+2  A: 
User.name.property.columns[0].type.length

Note, that SQLAlchemy supports composite properties, that's why columns is a list. It has single item for simple column properties.

Denis Otkidach