SQLAlchemy 几种查询方式总结
几种常见sqlalchemy查询:
from sqlalchemy import or_, and_, any_
简单查询
1 | print(session.query(User).all()) |
带条件查询
1 | print(session.query(User).filter_by(name='user1').all()) |
多条件查询
1 | print(session.query(User).filter(and_(User.name.like("user%"), User.fullname.like("first%"))).all()) |
sql过滤
1 | print(session.query(User).filter("id>:id").params(id=1).all()) |
关联查询
1 | print(session.query(User, Address).filter(User.id == Address.user_id).all()) |
聚合查询
1 | print(session.query(User.name, func.count('*').label("user_count")).group_by(User.name).all()) |
子查询
1 | stmt = session.query(Address.user_id, func.count('*').label("address_count")).group_by(Address.user_id).subquery() |
exists
1 | print(session.query(User).filter(exists().where(Address.user_id == User.id))) |
限制返回字段查询
1 | person = session.query(Person.name, Person.created_at,Person.updated_at).filter_by(name="zhongwei").order_by(Person.created_at).first() |
记录总数查询:
1 | from sqlalchemy import func |
with_entities()
通过使用with_entities()方法来获取要在结果中返回的列
查询制定的id列1
result = RiskDataModel.query.with_entities(RiskDataModel.id) # 返回BaseQuery
返回指定的两列1
result = RiskDataModel.query.with_entities(RiskDataModel.id, RiskDataModel.name)
并且去重1
result = RiskDataModel.query.with_entities(RiskDataModel.store_st_id).distinct().all()