如何在Python中用Peewee获取SQLite表中telegram_id的唯一记录?
获取SQLite表中唯一telegram_id的正确实现方法
你当前的代码问题在于只是构建了查询结构,没有实际执行查询并提取有效数据,导致无法得到预期的唯一telegram_id列表。以下是两种可行的修正方案:
方案一:使用原生SQL(sqlite3模块)
import sqlite3 def get_all_telegram_ids(): '''Returns all telegram_id from DB''' # 替换为你的数据库文件路径 conn = sqlite3.connect('your_database.db') cursor = conn.cursor() # 执行去重查询 cursor.execute("SELECT DISTINCT telegram_id FROM locations") # 获取所有结果,转换为纯ID列表(避免返回元组) telegram_ids = [row[0] for row in cursor.fetchall()] print(telegram_ids) conn.close() return telegram_ids
方案二:使用Peewee ORM
如果你的Locations是Peewee的模型类,需要执行查询并提取单个字段的值:
def get_all_telegram_ids(): '''Returns all telegram_id from DB''' # 执行查询,scalars()直接返回telegram_id的迭代器,转成列表 telegram_ids = list(Locations.select(Locations.telegram_id).distinct().scalars()) print(telegram_ids) return telegram_ids
关键说明
- 原生SQL方式:必须先建立数据库连接,执行查询后通过
fetchall()获取结果,再从元组中提取ID值。 - Peewee方式:
select().distinct()仅生成查询语句,scalars()方法会执行查询并返回指定字段的所有值,转成列表后就是你需要的唯一ID集合。
内容的提问来源于stack exchange,提问作者Алексей Зинин
相关产品推荐
相关产品推荐

