Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy getting column data types of query results

from sqlalchemy import create_engine, MetaData, ForeignKey

engine = create_engine("mysql://user:passwd@localhost/shema", echo=False)
meta = MetaData(engine, True)
conn = engine.connect()

tb_list = meta.tables["tb_list"]
tb_data = meta.tables["tb_data"]

tb_list.c.i_data.append_foreign_key( ForeignKey(tb_data.c.i_id) )

q = tb_list.outerjoin(tb_data).select()

res = conn.execute(q)

And now, how can I get columns type of query result res

One of decisions:

res._key_cache[ col_name ][0]

Do you know something else ?

like image 617
user272432 Avatar asked Feb 13 '10 15:02

user272432


People also ask

What does SQLAlchemy query return?

It returns exactly one result or raise an exception. It applies one or more ORDER BY criterion to the query and returns the newly resulting Query. It performs a bulk update query and updates rows matched by this query in the database.

How do I get column names in SQLAlchemy?

To access the column names we can use the method keys() on the result. It returns a list of column names. Since, we queried only three columns, we can view the same columns on the output as well.

What is PickleType?

PickleType. Holds Python objects, which are serialized using pickle. SchemaType. Mark a type as possibly requiring schema-level DDL for usage.

What is _sa_instance_state in SQLAlchemy?

_sa_instance_state is a non-database-persisted value used by SQLAlchemy internally (it refers to the InstanceState for the instance.


1 Answers

you'd say:

types = [col.type for col in q.columns]

the (compiled) statement is on the result too if you feel like digging:

types = [col.type for col in res.context.compiled.statement.columns]

if you want the DBAPI version of the types, which is a little more varied based on DBAPI:

types = [elem[1] for elem in res.cursor.description]

maybe we'll look into adding this kind of metadata more directly to the ResultProxy.

like image 65
zzzeek Avatar answered Sep 22 '22 18:09

zzzeek