python flask中使用or查询和and查询,还有同时使用or、and的情况

在 Flask 中处理数据库查询时,通常会结合使用 ORM 工具,例如 SQLAlchemy。以下是 or 查询、and 查询以及两者同时使用的示例。

文章目录

  • 基础准备
  • [1. 使用 or_ 查询](#1. 使用 or_ 查询)
  • [2. 使用 and_ 查询](#2. 使用 and_ 查询)
  • [3. 同时使用 or_ 和 and_](#3. 同时使用 or_ 和 and_)
  • [4. 更加复杂的嵌套查询](#4. 更加复杂的嵌套查询)

基础准备

假设有一个模型 User,定义如下:

python 复制代码
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import or_, and_

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    email = db.Column(db.String(100))
    age = db.Column(db.Integer)

1. 使用 or_ 查询

or_ 用于构造多个条件之间的"或"关系。例如,查询名字为 "Alice" 或者年龄大于 25 的用户:

python 复制代码
from sqlalchemy import or_

users = User.query.filter(or_(User.name == 'Alice', User.age > 25)).all()

2. 使用 and_ 查询

and_ 用于构造多个条件之间的"与"关系。例如,查询名字为 "Alice" 且年龄大于 25 的用户:

python 复制代码
from sqlalchemy import and_

users = User.query.filter(and_(User.name == 'Alice', User.age > 25)).all()

注意:在 SQLAlchemy 中,如果是简单的"与"关系,直接用逗号分隔条件即可,不需要显式使用 and_:

python 复制代码
users = User.query.filter(User.name == 'Alice', User.age > 25).all()

3. 同时使用 or_ 和 and_

假设查询的条件是:

● 名字为 "Alice" 或年龄大于 25,

● 并且邮箱以 "@example.com" 结尾。

可以这样组合:

python 复制代码
from sqlalchemy import or_, and_

users = User.query.filter(
    and_(
        or_(User.name == 'Alice', User.age > 25),
        User.email.like('%@example.com')
    )
).all()

4. 更加复杂的嵌套查询

例如,查询名字为 "Alice" 并且(年龄大于 25 或邮箱以 "@example.com" 结尾)的用户:

python 复制代码
users = User.query.filter(
    User.name == 'Alice',
    or_(
        User.age > 25,
        User.email.like('%@example.com')
    )
).all()
相关推荐
海棠AI实验室7 分钟前
第四章 项目目录结构:src/、configs/、data/、tests/ 的黄金布局
python·项目目录结构
左直拳1 小时前
将c++程序部署到docker
开发语言·c++·docker
爱笑的眼睛111 小时前
超越可视化:降维算法组件的深度解析与工程实践
java·人工智能·python·ai
崇山峻岭之间1 小时前
Matlab学习记录31
开发语言·学习·matlab
清铎2 小时前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划
ai_top_trends2 小时前
2026 年工作计划 PPT 横评:AI 自动生成的优劣分析
人工智能·python·powerpoint
你怎么知道我是队长2 小时前
C语言---输入和输出
c语言·开发语言
mmz12072 小时前
二分查找(c++)
开发语言·c++·算法
TDengine (老段)2 小时前
TDengine Python 连接器进阶指南
大数据·数据库·python·物联网·时序数据库·tdengine·涛思数据
你怎么知道我是队长2 小时前
C语言---文件读写
java·c语言·开发语言