Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sqlalchemy length of a string column

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'
like image 817
Anurag Uniyal Avatar asked Nov 22 '09 04:11

Anurag Uniyal


2 Answers

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.

like image 90
Denis Otkidach Avatar answered Oct 03 '22 23:10

Denis Otkidach


This should work (tested on my machine) :

print user.columns.name.type.length
like image 24
Pierre Bourdon Avatar answered Oct 03 '22 22:10

Pierre Bourdon