将SQL转换为SQLAlchemy
c = conn.cursor()
query = 'SELECT status, COUNT(id) FROM bar_baz where not name = 'Foo' and not name = 'Bar' GROUP BY status'
c.execute(query)
print c.fetchall()
class Instance(Base):
__tablename__ = 'instance'
id = Column(Integer, primary_key=True)
name = Column(String)
status = Column(String)
type = Column(String)
class Instance2(Base):
__tablename__ = 'instance_2'
id = Column(Integer, primary_key=True)
name = Column(String)
status = Column(String)
type = Column(String)
inc = Column(Integer)
我刚接触Flask的SQLAlchemy;虽然我明白SQLAlchemy可以简化SQL语法,让创建模型变得更简单,但有时候我们希望在前端以特定的方式展示数据。
我有一个查询,希望用SQLAlchemy的session.query和filter来实现,可能还需要分组。
我的查询是:
- mysql>
SELECT status, COUNT(id) FROM bar_baz where not name = 'Foo' and not name = 'Bar' GROUP BY status
select (select COUNT(id) FROM instance where not name = 'erf' and not tiername = 'wer' and type='app') as app, (select COUNT(1) FROM instance_2 where not name = 'visq' and not name = 'werf' and type='adc') as adc from dual;
我验证过这些查询在MySQL中可以正常工作;我想知道我们是否有类似的函数可以使用。
感兴趣的查询:
select (select COUNT(id) FROM instance where not name = 'erf' and not tiername = 'wer' and type='app') as app, (select COUNT(1) FROM instance_2 where not name = 'visq' and not name = 'werf' and type='adc') as adc from dual;`
1 个回答
4
对于第一个查询,使用 db.func.count
来生成计数的表达式。其他的内容应该从 文档 中很明显地看出来。
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()
对于第二个查询,使用 subquery()
来生成可以选择的查询。
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()