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.


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

conn.execute(query).keys()

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (Column, Index, Date, DateTime, Numeric, BigInteger, String, ForeignKey, Boolean)

Base = declarative_base()

class Project(Base):
    """sqlalchemy ORM for my table."""
    __tablename__ = "table1"
    id = Column("id", BigIntegerID, primary_key=True, autoincrement=True)
    date = Column("date", Date, nullable=False)
    value = Column("value", Numeric(20, 8))
    ...
    ...

Then this will return the columns names ['id', 'date', 'value', ...]:

Project.__table__.columns.keys()

Or this

Project.metadata.tables['table1'].columns.keys()

The difference is between ORM and non-ORM, not declarative, which is just a helper for the ORM.

Query has a method column_descriptions() that was added for this purpose::

http://www.sqlalchemy.org/docs/orm/query.html#sqlalchemy.orm.query.Query.column_descriptions

the example there seems like it has a typo, says q.columns but it should be q.column_descriptions (edit: just fixed it).


Just playing around, this syntax will give you all the columns (so to solve your problem, set query to look at one table/object only):

conn.execute(query)._metadata.keys