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

使用PeeWee操作SQLite时遇TypeError:expected str, not ModelBase

修复步骤

1. 核心错误:数据库初始化错误

错误根源在于创建SqliteDatabase实例时传入了错误参数。你需要传入数据库文件路径,而非pw.Model:

# 原错误代码
db = pw.SqliteDatabase(pw.Model)

# 修正后
db = pw.SqliteDatabase(file)  # file变量已定义为'network.db'

2. 补充模型字段定义

你的User和Status类缺少具体字段定义,导致create()方法无法找到对应属性。需添加字段:

class User(BaseModel):
    user_id = pw.CharField(primary_key=True)  # 根据需求选择字段类型,如IntegerField
    email = pw.CharField(unique=True)
    user_name = pw.CharField()
    user_last_name = pw.CharField()

class Status(BaseModel):
    status_id = pw.CharField(primary_key=True)
    user_id = pw.ForeignKeyField(User, backref='statuses')  # 外键关联User表
    status_text = pw.TextField()

3. 修正数据列表与索引问题

  • users列表中每个元组只有3个元素,但User.create()尝试访问第4个元素(account[3]),导致索引越界。需补充为4个元素:
users = [
    ('user1', 'test1@example.com', 'name1', 'last1'),
    ('user2', 'test2@example.com', 'name2', 'last2'),
    ('user3', 'test3@example.com', 'name3', 'last3')
]
  • 所有类似user1、test1的未定义变量需替换为实际值(字符串/数字)。

4. 修复代码结构问题

  • 移除冗余的save()调用:User.create()和Status.create()已自动将实例保存到数据库,无需额外调用save()。
  • 修正try-except块的缩进与语法:
# 示例:用户创建的try-except
for account in users:
    try:
        with db.transaction():
            User.create(
                user_id=account[0],
                email=account[1],
                user_name=account[2],
                user_last_name=account[3]
            )
    except Exception as e:
        print(f"创建用户失败: {str(e)}")
  • 确保status列表的循环代码缩进正确,且except块有具体处理逻辑。

完整修正后的代码示例

import os
import peewee as pw

file = 'network.db'
if os.path.exists(file):
    os.remove(file)

# 修正数据库初始化
db = pw.SqliteDatabase(file)

class BaseModel(pw.Model):
    class Meta:
        database = db

class User(BaseModel):
    user_id = pw.CharField(primary_key=True)
    email = pw.CharField(unique=True)
    user_name = pw.CharField()
    user_last_name = pw.CharField()

class Status(BaseModel):
    status_id = pw.CharField(primary_key=True)
    user_id = pw.ForeignKeyField(User, backref='statuses')
    status_text = pw.TextField()

def main():
    db.connect()
    db.execute_sql('PRAGMA foreign_keys = ON;')
    db.create_tables([User, Status])
 
    users = [
        ('user1', 'test1@example.com', 'name1', 'last1'),
        ('user2', 'test2@example.com', 'name2', 'last2'),
        ('user3', 'test3@example.com', 'name3', 'last3')
    ]

    for account in users:
        try:
            with db.transaction():
                User.create(
                    user_id=account[0],
                    email=account[1],
                    user_name=account[2],
                    user_last_name=account[3]
                )
        except Exception as e:
            print(f"创建用户失败: {str(e)}")

    status = [
        ('status1', 'user1', 'text1'),
        ('status2', 'user2', 'text2'),
        ('status3', 'user3', 'text3')
    ]

    for message in status:
        try:
            with db.transaction():
                Status.create(
                    status_id=message[0],
                    user_id=message[1],
                    status_text=message[2]
                )
        except Exception as e:
            print(f"创建状态失败: {str(e)}")

    db.close()

main()

内容的提问来源于stack exchange,提问作者Parker Johnson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 15:45:40