You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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,提问作者Алексей Зинин

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:20:33