SqlAlchemy动态查询

时间:2018-10-22 22:05:15

标签: python sqlalchemy flask-sqlalchemy

我将SqlAlchemy用作与Oracle数据库的接口,我想知道是否有可能,如果可以,怎么办。我正在尝试构建一个获取数据聚合的查询,然后根据随Flask请求传递的参数向查询中动态添加列。这是一个示例查询(从我的实际查询中简化):

db.session.query(
    func.count(Batch.batch_id).label('count'),
    Category.product_title.label('product_title'),
) \
.join(Category, Category.category_id == Batch.category_id)
.filter(Batch.date <= end_date) \
.filter(Batch.date >= start_date)
.group_by(Category.product_title)
.all()

这是我查询的起点。但是基于请求参数,我想修改此基本查询,使其看起来像是扩展查询:

LateB = db.aliased(Batch)

db.session.query(
    func.count(Batch.batch_id).label('count'),
    func.count(distinct(LateB.batch_id).label('late'),
    Category.product_title.label('product_title'),
) \
.join(Category, Category.category_id == Batch.category_id) \
.outerjoin(LateB, (LateB.batch_id == Batch.batch_id) & (LateB.date <= some_date_in_the_past)) \
.filter(Batch.date <= end_date) \
.filter(Batch.date >= start_date)
.group_by(Category.product_title)
.all()

我的目标是创建基本查询,然后对其进行动态修改,使其最终看起来像扩展查询。任何人都可能有任何想法,如果有的话,他们可以指出一些想法或建议吗?

谢谢! 道格

0 个答案:

没有答案
相关问题