Background
When I want to create a dictionary to map the column name to values in a result, I need to list out each column individually
result = self.session.query(Project)\
.join(Deadline)\
.values(Project.project_id, Project.project_name,
Project.project_root, Deadline.deadline_time)
output = []
for row in result:
r = {}
r['project_id'] = row.project_id
r['project_name'] = row.project_name
r['project_root'] = row.project_root
r['deadline_time'] = row.deadline_time
output.append(r)
return output
The Models are ORM-mapped, and not SQLAlchemy core.
class Deadline(Base):
__tablename__ = 'deadline'
deadline_id = Column(Integer, primary_key = True)
deadline_time = Column(String, nullable = False)
class Project(Base):
__tablename__ = 'project'
project_id = Column(Integer, primary_key = True)
project_name = Column(String, nullable = False)
project_root = Column(String, nullable = False)
deadline_id = Column(Integer, ForeignKey("deadline.deadline_id"), nullable=False)
deadline = relationship("Deadline", primaryjoin = "Project.deadline_id == Deadline.deadline_id", backref=backref("project", uselist=False))
Question
This is not efficient for a table with many columns, nor can I re-use the same code for other tables.
I tried the following but could not get the column name
column_names = [c["name"] for c in result.column_descriptions]
return [dict(zip(column_names, row)) for row in result.all()]
result.__table__.columns.keys()
Edit 1
There are a few similar questions about converting SQLAlchemy result into dict. As per the code above, result.__table__.columns.keys()
does not work for ORM-mapped models.