以下是使用Peewee和MySQL进行随机查询数据并分页的示例代码:
import random
from peewee import *
from models import MyModel # 假设已经定义了模型
# 连接到MySQL数据库
mysql_db = MySQLDatabase('mydatabase', user='myuser', password='mypassword',
host='localhost', port=3306)
# 定义每页显示的记录数和当前页码
PAGE_SIZE = 10
page_num = 1
# 随机选取数据并分页
query = MyModel.select().order_by(fn.Random())
total_count = query.count()
offset = (page_num - 1) * PAGE_SIZE
query = query.offset(offset).limit(PAGE_SIZE)
# 执行查询并打印结果
for row in query:
print(row.id, row.name, row.age)
# 输出分页信息
total_page = (total_count + PAGE_SIZE - 1) // PAGE_SIZE
print(f"第{page_num}/{total_page}页,共{total_count}条记录")
在上面的示例中,我们首先连接到MySQL数据库,然后使用 fn.Random()
函数对查询结果进行随机排序。然后,我们计算出总记录数和当前页的偏移量,并使用 offset()
和 limit()
方法进行分页。最后,我们遍历查询结果并打印每条记录的 id、name 和 age 字段。
同时,我们还输出了分页信息,包括总页数、当前页码和总记录数。