Trey
Trey

Reputation: 201

SQLAlchemy _asdict() method returns only one column

I am trying to convert the rows returned in a SQLAlchemy query to dictionaries. When I try to use the ._asdict() method, I am only getting a key-value pair for the first column in my results.

Is there something else I should do to create a key-value pair in the dictionary for all columns in the result row?

class Project(db.Model):

    __tablename__ = 'entries'

    id = db.Column(db.Integer, primary_key=True)
    time_start = db.Column(db.DateTime(timezone=False))
    time_end = db.Column(db.DateTime(timezone=False))
    name = db.Column(db.String(256), nullable=True)
    analyst = db.Column(db.String(256), nullable=True)

    def __init__(id, time_start, time_end, project_name, analyst):
        self.id = id
        self.time_start = time_start
        self.time_end = time_end
        self.name = name
        self.analyst = analyst

latest_projects = db.session.query((func.max(Project.time_end)), Project.analyst).group_by(Project.analyst)

for row in latest_projects.all():
    print (row._asdict())

{'analyst': 'Bob'}
{'analyst': 'Jane'}
{'analyst': 'Fred'}

I was expecting to see results like this...

{'analyst': 'Bob', 'time_end': '(2018, 11, 21, 14, 55)'}
{'analyst': 'Jane', 'time_end': '(2017, 10, 21, 08, 00)'}
{'analyst': 'Fred', 'time_end': '(2016, 09, 06, 01, 35)'}

Upvotes: 1

Views: 5252

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121594

You haven't named the func.max() column, so there is no name to use as a key in the resulting dictionary. Aggregate function columns are not automatically named, even when aggregating a single column; that you based that column on on the time_end column doesn't matter here.

Give that column a label:

latest_projects = db.session.query(
    func.max(Project.time_end).label('time_end'),
    Project.analyst
).group_by(Project.analyst)

Demo:

>>> latest_projects = db.session.query(
...     func.max(Project.time_end).label('time_end'),
...     Project.analyst
... ).group_by(Project.analyst)
>>> for row in latest_projects.all():
...     print (row._asdict())
...
{'time_end': datetime.datetime(2018, 11, 21, 14, 55), 'analyst': 'Bob'}
{'time_end': datetime.datetime(2016, 9, 6, 1, 35), 'analyst': 'Fred'}
{'time_end': datetime.datetime(2017, 10, 21, 8, 0), 'analyst': 'Jane'}

Upvotes: 2

Related Questions