在SQLAlchemy中对“黑盒子”查询进行排序?

时间:2017-03-21 03:10:40

标签: python sqlalchemy

我经常使用像这样的查询:

def activityQuery(inActivity, inOrder='time'):
    a1 = gDB.session.query(Activity.unitID, Activity.activity, func.max(Activity.occurredAt).label("maxOA")) \
        .group_by(Activity.unitID) \
        .subquery()
    a2 = aliased(Activity, name="a2")
    u = aliased(Unit, name="u")
    q = gDB.session.query(u).select_from(a1) \
        .join(a2, and_(a2.unitID == a1.c.unit_id, a2.occurredAt == a1.c.maxOA)) \
        .join(u, u.id == a2.unitID).filter(a2.activity.in_(inActivity))

    if inOrder == 'time':
        q = q.order_by(a2.occurredAt)
    elif inOrder == 'address':
        q = q.order_by(u.street, u.unitNumber)
    return q

正如您所看到的,我正在传递一个参数来指示所需的排序,但我真的想在调用activityQuery()之后指定排序。这可能吗?显然,a2u之类的符号超出了此调用的范围。是否有另一种方法来指定如何订购生成的查询?谢谢!

1 个答案:

答案 0 :(得分:1)

def timeOrder(q, u, a1, a2): return q.order_by(a2.occurredAt) def addressOrder(q, u, a1, a2): return q.order_by(u.street, u.unitNumber) def activityQuery(inActivity, inOrder=timeOrder): a1 = gDB.session.query(Activity.unitID, Activity.activity, func.max(Activity.occurredAt).label("maxOA")) \ .group_by(Activity.unitID) \ .subquery() a2 = aliased(Activity, name="a2") u = aliased(Unit, name="u") q = gDB.session.query(u).select_from(a1) \ .join(a2, and_(a2.unitID == a1.c.unit_id, a2.occurredAt == a1.c.maxOA)) \ .join(u, u.id == a2.unitID) \ .filter(a2.activity.in_(inActivity)) return inOrder(q, u, a1, a2) activityQuery(..., inOrder=addressOrder) 接受一个可调用的 inOrder

public