SQLAlchemy中filter函数的使用

简介: SQLAlchemy中filter函数的使用

filter过滤数据

在SQLAlchemy中,filter 方法用于在查询中对数据进行过滤,以获取符合特定条件的记录。这方法允许你构建 SQL 查询中的 WHERE 子句,并可以组合多个条件来过滤数据。

方法及使用示例

以下对一些常用的过滤条件进行解释,并且这些过滤条件都是只能通过filter方法实现的:

基本过滤

使用 filter 方法来获取满足指定条件的记录。

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('mysql://user:password@localhost/dbname')
Session = sessionmaker(bind=engine)
session = Session()
# 查询用户名为'John'的用户
results = session.query(User).filter(User.name == 'John').all()

多个条件的过滤

可以组合多个条件来过滤数据,使用 and_or_ 来构建复杂的条件表达式。

from sqlalchemy import and_, or_
# 查询用户名为'John'且年龄大于等于30的用户
results = session.query(User).filter(and_(User.name == 'John', User.age >= 30)).all()
# 查询用户名为'John'或年龄大于等于30的用户
results = session.query(User).filter(or_(User.name == 'John', User.age >= 30)).all()

模糊查询

使用 like 方法进行模糊查询。

# 查询用户名以'J'开头的用户
results = session.query(User).filter(User.name.like('J%')).all()

IN查询

使用 in_ 方法来查询某个字段是否包含在一组值中。

values = ['John', 'Alice', 'Bob']
results = session.query(User).filter(User.name.in_(values)).all()

空值和非空值

使用 is_ 方法来查询空值或非空值。

# 查询没有邮箱地址的用户
results = session.query(User).filter(User.email.is_(None)).all()
# 查询有邮箱地址的用户
results = session.query(User).filter(User.email.isnot(None)).all()

代码演示

from random import randint
from uuid import uuid4
from sqlalchemy import Column,Integer,String,Float,Text,and_,or_
from db_util import Base,Session
class Article(Base):
  __tablename__ = 't_article'
  id = Column(Integer,primary_key=True,autoincrement=True)
  title = Column(String(50),nullable=False)
  price = Column(Float,nullable=False)
  content = Column(Text)
  def __repr__(self):
    return f"<Article(title:{self.title} price:{self.price} content:{self.content})>"
def create_data():
  with Session() as ses:
    for i in range(10):
      if i%2 == 0:
        art = Article(title = f'title{i+1}',price=randint(1,100),content = uuid4())
      else:
        art = Article(title = f'TITLE{i+1}',price=randint(1,100))
      ses.add(art)
    ses.commit()
def query_data():
  with Session() as ses:
    # rs = ses.query(Article).filter_by(id=1).first()
    rs = ses.query(Article).filter(Article.id == 1).first()
    print(rs)
def query_data_equal():
  with Session() as ses:
    rs = ses.query(Article).filter(Article.title == 'title2').first()
    print(rs)
def query_data_not_equal():
  with Session() as ses:
    rs = ses.query(Article).filter(Article.title != 'title2').all()
    print(rs)
def query_data_like():
  with Session() as ses:
    # select * from t_article where title like 'title%';
    rs = ses.query(Article).filter(Article.title.like('title%')).all()
    for r in rs:
      print(r)
def query_data_in():
  with Session() as ses:
    rs = ses.query(Article).filter(Article.title.in_(['title1','title3','title6'])).all()
    for r in rs:
      print(r)
def query_data_not_in():
  with Session() as ses:
    rs = ses.query(Article).filter(~ Article.title.in_(['title1','title3','title6'])).all()
    for r in rs:
      print(r)
def query_data_null():
  with Session() as ses:
    rs = ses.query(Article).filter(Article.content == None).all()
    for r in rs:
      print(r)
def query_data_not_null():
  with Session() as ses:
    rs = ses.query(Article).filter(Article.content != None).all()
    for r in rs:
      print(r)
def query_data_and():
  with Session() as ses:
    # rs = ses.query(Article).filter(Article.title !='title4' and Article.price >8 ).all() 
    # rs = ses.query(Article).filter(Article.title !='title4',Article.price >50 ).all() 
    rs = ses.query(Article).filter(and_(Article.title !='title4',Article.price >50) ).all() 
    for r in rs:
      print(r)
def query_data_or():
  with Session() as ses: 
    rs = ses.query(Article).filter(or_(Article.title =='title4',Article.price >50) ).all() 
    for r in rs:
      print(r)
if __name__ == '__main__':
  # Base.metadata.create_all()
  # create_data()
  # query_data()
  # query_data_equal()
  # query_data_not_equal()
  # query_data_like()
  # query_data_in()
  # query_data_not_in()
  # query_data_null()
  # query_data_not_null()
  # query_data_and()
  query_data_or()

代码刨析

  1. Article 模型类定义
  • 你定义了一个名为 Article 的模型类,它映射到了数据库中的 t_article 表格,包括了 idtitlepricecontent 四个字段。
  1. create_data 函数
  • 该函数在数据库中插入了一些示例数据,包括了标题、价格和内容。其中,标题的命名规则是 title{i+1} 或者 TITLE{i+1},价格是一个随机的整数,内容使用了 uuid4()成。
  1. query_data 函数
  • 该函数查询了 id 为 1 的记录。
  1. query_data_equal 函数
  • 该函数查询了标题等于 'title2' 的第
  1. query_data_not_equal 函数
  • 该函数查询了标题不等于 'title2' 的所有记录。
  1. query_data_like 函数
  • 该函数查询了标题以 'title' 开头的所有记录。
  1. query_data_in 函数
  • 该函数查询了标题在 ['title1','title3','title6'] 中的所有记录。
  1. query_data_not_in 函
  • 该函数查询了标题不在 ['title1','title3','title6'] 中的所有记录。
  1. query_data_null 函
  • 该函数查询了内容为 None 的所有记录。
  1. query_data_not_null 函
  • 该函数查询了内容不为 None 的所有记录。
  1. query_data_and 函
  • 该函数查询了标题不等于 'title4' 且价格大于 50 的所有记录。
  1. query_data_or 函
  • 该函数查询了标题等于 'title4' 或者价格大于 50 的所有记录。
相关文章
|
6天前
|
前端开发 JavaScript 数据处理
(详解及使用)import()函数和import语句
(详解及使用)import()函数和import语句
97 1
|
8月前
|
数据库 索引 Python
SQLAlchemy列参数的使用和query函数的使用
SQLAlchemy列参数的使用和query函数的使用
|
Python
运行项目时flask_sqlalchemy报错AttributeError: ‘LocalStack‘ object has no attribute ‘__ident_func__‘
1.原因 是由于flask_sqlalchemy版本不匹配导致的,我们需要自动获取正确的包版本
656 1
|
存储 SQL 数据可视化
Python 之 Pandas merge() 函数、set_index() 函数、drop_duplicates() 函数和 tolist() 函数
Python 之 Pandas merge() 函数、set_index() 函数、drop_duplicates() 函数和 tolist() 函数
FastAPI(22)- Pydantic Model 结合 Union、List 的使用场景
FastAPI(22)- Pydantic Model 结合 Union、List 的使用场景
442 0
FastAPI(22)- Pydantic Model 结合 Union、List 的使用场景
|
Serverless 索引 Python
内置函数 -- filter 和 map
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
107 0
rxjs里scan和mergeScan operators的用法
rxjs里scan和mergeScan operators的用法
126 0
rxjs里scan和mergeScan operators的用法
rxjs里scan operators的用法
rxjs里scan operators的用法
60 0
rxjs里scan operators的用法
|
Python 数据库管理 数据库
|
Python
django orm如何作一个优雅一点的filter?
如果有N多fitler条件, 单独放在一个长语句里显然不好看。 还好, django支持字典方式的过滤条件, 写法大约与单独的长语里差不多。 如下: def get_queryset(self): filter_dict = dict() if self.
1098 0