原文出处:sqlalchemy的filter使用
from flask import Flask, jsonify, json from sqlalchemy import create_engine, Column, Integer, String, DateTime, Float, func, and_, or_ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from datetime import datetime # 连接数据库字符串 DB_URI = "mysql://root:123456@127.0.0.1/pyDemo" engine = create_engine(DB_URI) # 判断是否连接成功 engine.connect() # 创建ORM Base = declarative_base(engine) # 创建回话 session = sessionmaker(engine)() class Article(Base): # 表名字 __tablename__ = 'Article' # 列 id = Column(Integer, primary_key=True, autoincrement=True) # read_count = Column(Integer, default=0) title = Column(String(50), default='1111') content = Column(String(50)) price = Column(Float, nullable=False) # 查询条件 # 1.equal res = session.query(Article).filter(Article.id == 21).first() # print(res) # 2.notequal res = session.query(Article).filter(Article.id != 21).all() # print(res) # 3.like & ilike不区分大小写 res = session.query(Article).filter(Article.title.like('title%')).all() # print(res) # 4.in res = session.query(Article).filter(Article.title.in_(['title0', 'title1'])).all() # print(res) # 5.not in res = session.query(Article).filter(~Article.title.in_(['title0', 'title1'])).all() # print(res) res = session.query(Article).filter(Article.title.notin_(['title0', 'title1'])).all() # print(res) # 6.isnull res = session.query(Article).filter(Article.content == None).all() # print(res) # 7.is not null res = session.query(Article).filter(Article.content != None).all() # print(res) # 8 and res = session.query(Article).filter(Article.content == None, Article.title.notin_(['title0', 'title1'])).all() # print(res) res = session.query(Article).filter(and_(Article.content == None, Article.title.notin_(['title0', 'title1']))).all() # print(res) # 9 or res = session.query(Article).filter( or_(Article.content != None, Article.title.notin_(['title0', 'title1', 'title5']))).all() print(res)