sqlalchemy.exc.IntegrityError 受到打击:(IntegrityError)约束失败“INSERT INTO 用户" [英] struck at sqlalchemy.exc.IntegrityError: (IntegrityError) constraint failed 'INSERT INTO users

查看:43
本文介绍了sqlalchemy.exc.IntegrityError 受到打击:(IntegrityError)约束失败“INSERT INTO 用户"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 sqlite 数据库,并且我在这个要点中声明了模型

I am using sqlite database and I declared the models as in this gist

https://gist.github.com/mmahesh/7245561

我添加了一个带有事务管理器的模型实例

I have added a model instance with transaction manager as

with transaction.manager:
    model = Users(username='example',name='Example', email_primary='m@m.com', _password='example')
    DBSession.add(model)

每当我执行 initialize_sample_db development.ini 时,就会出现这个错误

Whenever I execute initialize_sample_db development.ini, this error shows up

sqlalchemy.exc.IntegrityError: (IntegrityError) constraint failed 'INSERT INTO users (name, username, email_primary, email_secondary, _password, bio) VALUES (?, ?, ?, ?, ?, ?)' ('Example', 'example', 'm@m.com', None, 'example', None )

附加信息:当我使用 sqlite3 命令工具并在 '.d' 命令之后我得到

Additional Information: when i use sqlite3 command tool and after '.d' command i get

PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
COMMIT;

提前致谢

推荐答案

在表 users 中,您已将列 id 定义为主键.但是,在您的 INSERT 语句中,您没有提供 id.

In table users you have defined column id as primary key. However, in your INSERT statement you do not provide id.

如果 id 是自动递增列,那完全没问题 - 但事实并非如此.

That would be totally fine if id was auto-increment column - but it is not.

解决方法是添加sqlite_autoincrement=True 进入您的 users 表定义.

Solution is to add sqlite_autoincrement=True into your users table definition.

此外,您的 users 表定义似乎过于严格 - 您要求大多数字段不可为空.这取决于您的任务,但有时过于严格可能是个坏主意 - 如果您忘记(或根本不想)填写其中一个字段,也会导致违反约束.

Also, your users table definitions seems to be too strict - you require most fields to be non-nullable. It depends on your task, but sometimes being too strict can be bad idea - it will also cause constraint violation if you forgot (or simply don't want) to fill one of those fields.

这篇关于sqlalchemy.exc.IntegrityError 受到打击:(IntegrityError)约束失败“INSERT INTO 用户"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆