Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get column names from SQLAlchemy result (declarative syntax)

I am working in a pyramid project and I've the table in SQLAlchemy in declarative syntax

"""models.py""" class Projects(Base):     __tablename__ = 'projects'     __table_args__ = {'autoload': True} 

I get the results by using

""""views.py""" session = DBSession() row_data = session.query(Projects).filter_by(id=1).one() 

How can I get the column names from this result.

PS: I am unable to use this method since I am using the declarative syntax.

like image 337
Sukumar Avatar asked Jun 23 '11 14:06

Sukumar


People also ask

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.

How do I get column names in Python using SQL?

Approach: Connect to a database using the connect() method. Create a cursor object and use that cursor object created to execute queries in order to create a table and insert values into it. Use the description keyword of the cursor object to get the column names.

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.

What is all () in SQLAlchemy?

method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.


1 Answers

You can do something similar to Foo Stack's answer without resorting to private fields by doing:

conn.execute(query).keys() 
like image 125
prolibertas Avatar answered Sep 27 '22 20:09

prolibertas