Rodolphe LAMPE
Rodolphe LAMPE

Reputation: 1518

Can SQLAlchemy return a grouped_by query as a dictionary?

I have a Trace model and I wonder if I can do better than that:

traces = Trace.query.filter(some_filtering).all()
return {
        student_id: [trace for trace in traces if trace.student_id == student_id]
        for student_id in student_ids
    }

Can SQLAlchemy return a dictionary directly using the grouped_by variable as keys of the dictionary?

Upvotes: 4

Views: 2295

Answers (2)

mad_
mad_

Reputation: 8273

traces = Trace.query.grouped_by(Trace.id).filter(some_filtering).all()
traces_dict_list=[]
for trace_row in traces:
    traces_dict_list.append(trace_row .__dict__)

Upvotes: -2

SuperShoot
SuperShoot

Reputation: 10871

Not pure SQLAlchemy but combined with itertools.groupby:

qry = Trace.query.order_by(Trace.student_id)
grouped = {k: list(g) for k, g in itertools.groupby(qry, lambda t: t.student_id)}

Upvotes: 2

Related Questions