文章内容

2024/2/2 0:17:31,作 者: 黄兵

SQLAlchemy 重复过滤查询

如果我们需要对 SQLAlchemy 模型中的某一列数据进行去重,你可以使用 distinct 函数。

以下是一个示例,演示如何使用 distinct 去重 phone_number

from sqlalchemy import distinct

# 假设你有一个查询对象
query = db.session.query(SMSReceiveHistory.phone_number).distinct()

# 执行查询并获取去重的 phone_number 列表
unique_phone_numbers = [result[0] for result in query.all()]

# 现在 unique_phone_numbers 中包含了去重后的 phone_number 列表

如果希望在查询的同时获取其他列的信息,可以将它们添加到 query 中。

distinct 方法可以应用于查询对象的一个或多个列,以确保返回唯一的结果。以下是一些关于如何在 SQLAlchemy 模型中使用 distinct 的详细讲解和示例:

1. 基本使用:

from sqlalchemy import distinct

# 假设你有一个查询对象
query = db.session.query(SMSReceiveHistory.phone_number).distinct()

# 执行查询并获取去重的 phone_number 列表
unique_phone_numbers = [result[0] for result in query.all()]

# unique_phone_numbers 中包含了去重后的 phone_number 列表

2. 多列去重:

# 假设你有一个查询对象,想要对 phone_number 和 year 列进行去重
query = db.session.query(SMSReceiveHistory.phone_number, SMSReceiveHistory.year).distinct()

# 执行查询并获取去重的结果列表
unique_results = query.all()

3. 添加过滤条件:

# 在查询中添加过滤条件,例如只获取某一年份的去重 phone_number
query = db.session.query(SMSReceiveHistory.phone_number).filter(SMSReceiveHistory.year == '2022').distinct()

# 执行查询并获取去重的 phone_number 列表
unique_phone_numbers_2022 = [result[0] for result in query.all()]

4. 使用 distinctorder_by

# 对 phone_number 列进行去重,并按照 phone_number 进行升序排序
query = db.session.query(SMSReceiveHistory.phone_number).distinct().order_by(SMSReceiveHistory.phone_number)

# 执行查询并获取去重并排序后的 phone_number 列表
unique_phone_numbers_sorted = [result[0] for result in query.all()]

这些示例展示了在 SQLAlchemy 模型中如何使用 distinct 方法以及如何与其他查询操作结合使用。


其它相关推荐:

1、python Thread长时间运行问题

2、python 读写csv文件示例

3、python 验证IP地址

4、python字符串相关操作总结

5、python logging.warn 和 logging.warning 的区别

分享到:

发表评论

评论列表