代码之家  ›  专栏  ›  技术社区  ›  Rodolphe LAMPE

sqlAlchemy是否可以将分组查询作为字典返回?

  •  2
  • Rodolphe LAMPE  · 技术社区  · 6 年前

    我有一个 Trace 我想知道我是否能做得更好:

    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
        }
    

    sqlAlchemy是否可以直接使用 grouped_by 变量作为字典的键?

    2 回复  |  直到 6 年前
        1
  •  0
  •   SuperShoot npburns224    6 年前

    不是纯SQL炼金术,而是与 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)}
    
        2
  •  -1
  •   mad_    6 年前
    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__)