Convert SQL to SQL alchemy

前端 未结 1 1818
执笔经年
执笔经年 2021-01-16 10:59

I am new to Flask SQl alchemy; Though i understand that alchemy abstracts the sql syntax and makes things easy while creating models; there could be times when we want to vi

相关标签:
1条回答
  • 2021-01-16 11:28

    For the first query, use db.func.count to produce the count expression. Everything else should be obvious from the docs.

    status_counts = db.session.query(BarBaz.status, db.func.count(BarBaz.id).label('count_id')
    ).filter(db.not_(db.or_(BarBaz.name == 'Foo', BarBaz.name == 'Bar'))
    ).group_by(BarBaz.status
    ).all()
    

    For the second query, use subquery() to produce selectable queries.

    sub_app = db.session.query(db.func.count(Instance.id).label('app')
    ).filter(db.not_(db.or_(Instance.name == 'erf', Instance.tiername == 'wer')), Instance.type == 'app'
    ).subquery()
    
    sub_adc = db.session.query(db.func.count(Instance.id).label('adc')
    ).filter(db.not_(db.or_(Instance2.name == 'visq', Instance2.name == 'werf')), Instance2.type == 'adc'
    ).subquery()
    
    out = db.session.query(sub_app.c.app, sub_adc.c.adc).all()
    
    0 讨论(0)
提交回复
热议问题