How to have the python type and the constraints of a sqlalchemy column?

By doing this :

    columns = [[column.name, column.type] for column in inspect(table).c]
    print(columns)

I managed to get the name and the type of a column. But the type I get is on the sqlalchemy format, not in python format. I would also like to know if the table is nullable.

For example, if we have this column :

    username = Column(String(45), nullable=False)

I would like to get something like :

    ["username", str, 45, False]

Upvotes: 0

Views: 311

Answers (1)

snakecharmerb
snakecharmerb

Reputation: 55679

You can get the Python type from the column's type's python_type attribute, length from the type, nullable from the column:

>>> username = sa.Column(sa.String(45), nullable=False)
>>> username.type.python_type
<class 'str'>
>>> username.type.length
45
>>> username.nullable
False

Upvotes: 1

Related Questions