IntegrityError:错误:“user_id”列中的空值违反非空约束
Posted
技术标签:
【中文标题】IntegrityError:错误:“user_id”列中的空值违反非空约束【英文标题】:IntegrityError: ERROR: null value in column "user_id" violates not-null constraint 【发布时间】:2016-01-18 11:05:51 【问题描述】:使用:postgres (PostgreSQL) 9.4.5
我刚刚将sqlite3
数据库迁移到postgresql
数据库。出于某种原因,自从这次迁移以来,当我尝试创建用户时,出现了关于 user_id
(这是一个主键)的错误。在sqlite3
之前,这不是问题。我花了一些时间浏览文档和堆栈问题,但仍然感到困惑。
内部api.create_user()
:
api.create_user(username ='lola ', firstname ='cats ', lastname ='lcatk', email='cags@falc.com')
sqlalchemy db 型号:
class User(Base):
__tablename__ = 'users'
#user_id = Column(Integer, primary_key=True)
#changed to:
id = Column(Integer, primary_key=True)
username = Column(String(50))
firstname = Column(String(50))
lastname = Column(String(50))
email = Column(String(300))
password = Column(String(12))
institution = Column(String(50))
def __init__(self, username, firstname, lastname, email):
self.username = username
self.firstname = firstname
self.lastname = lastname
self.email = email
def __repr__(self):
return "<User(username ='%s', firstname ='%s', lastname ='%s', email='%s')>" % (self.username, self.firstname, self.lastname, self.email)
金字塔views.py:
@view_config(#code supplying the template and etc.)
def save_assessment_result(request):
with transaction.manager:
username = request.params['username']
firstname = request.params['firstname']
lastname = request.params['lastname']
email = request.params['email']
user = api.create_user(username, firstname, lastname, email)
#mode code to commit and etc.
transaction.commit()
return HTTPCreated()
postgres Server.log:
ERROR: null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (null, lola , cats , lcatk, cags@falc.com, null, null, 2015-10-19 23:02:21.560395).
STATEMENT: INSERT INTO users (username, firstname, lastname, email, password, institution, created_on) VALUES ('lola ', 'cats ', 'lcatk', 'cags@falc.com', NULL, NULL, '2015-10-19T23:02:21.560395'::timestamp) RETURNING users.user_id
追溯:
015-10-19 19:02:21,563 ERROR [pyramid_debugtoolbar][Dummy-3] Exception at http://0.0.0.0:6432/save_assessment_result
File "/Users/ack/code/venv/NotssWEB/notssweb/views/default.py", line 61, in save_assessment_result
assessment = api.retrieve_assessment(assessment_id)
File "/usr/local/lib/python2.7/site-packages/notssdb/api/object.py", line 112, in retrieve_assessment
filter(Assessment.assessment_id == something_unique).one()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2473, in one
ret = list(self)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/query.py", line 2515, in __iter__
self.session._autoflush()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1292, in _autoflush
util.raise_from_cause(e)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 1282, in _autoflush
self.flush()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2004, in flush
self._flush(objects)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2122, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 60, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/session.py", line 2086, in _flush
flush_context.execute()
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 373, in execute
rec.execute(self)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/unitofwork.py", line 532, in execute
uow
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 174, in save_obj
mapper, table, insert)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/orm/persistence.py", line 781, in _emit_insert_statements
execute(statement, params)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 914, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/sql/elements.py", line 323, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1010, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1146, in _execute_context
context)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1341, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/base.py", line 1139, in _execute_context
context)
File "/usr/local/lib/python2.7/site-packages/sqlalchemy/engine/default.py", line 450, in do_execute
cursor.execute(statement, parameters)
IntegrityError: (raised as a result of Query-invoked autoflush; consider using a session.no_autoflush block if this flush is occurring prematurely) (psycopg2.IntegrityError) null value in column "user_id" violates not-null constraint
DETAIL: Failing row contains (null, lola , cats , lcatk, cags@falc.com, null, null, 2015-10-19 23:02:21.560395).
[SQL: 'INSERT INTO users (username, firstname, lastname, email, password, institution, created_on) VALUES (%(username)s, %(firstname)s, %(lastname)s, %(email)s, %(password)s, %(institution)s, %(created_on)s) RETURNING users.user_id'] [parameters: 'username': u'lola ', 'firstname': u'cats ', 'lastname': u'lcatk', 'institution': None, 'created_on': datetime.datetime(2015, 10, 19, 23, 2, 21, 560395), 'password': None, 'email': u'cags@falc.com']
2015-10-19 19:02:21,564 DEBUG [notssweb][Dummy-3] route matched for url http://0.0.0.0:6432/_debug_toolbar/exception?token=a30c0989db02aeff9cd2&tb=4459323984; route_name: 'debugtoolbar', path_info: u'/_debug_toolbar/exception', pattern: '/_debug_toolbar/*subpath', matchdict: 'subpath': (u'exception',), predicates: '
【问题讨论】:
评论不用于扩展讨论;这个对话是moved to chat。 由于您似乎在聊天中解决了问题,请添加您的答案并关闭此问题:-) 【参考方案1】:首先。
我将数据库中的 id 命名约定从 user_id
更改为简单的 id
(对于所有其他人都是如此)。
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
第二。 在将原始 sqlite db 文件转储到 postgres(来自 sqlite3 --> postgres)而不是在 postgres 中创建数据库时发现了该问题。 所以,我在 SQLAlchemy 中运行了原始代码,但这次指向的是 postgres db:
engine = create_engine('postgresql://localhost/some_db')
这创建了所需的关系和序列(通过 \ds
在 postgres 中显示,psql
)。问题已解决。
【讨论】:
以上是关于IntegrityError:错误:“user_id”列中的空值违反非空约束的主要内容,如果未能解决你的问题,请参考以下文章
IntegrityError:错误:“user_id”列中的空值违反非空约束