IntegrityError:错误:列“ user_id”中的值为空。违反非空约束 [英] IntegrityError: ERROR: null value in column "user_id" violates not-null constraint

查看:137
本文介绍了IntegrityError:错误:列“ user_id”中的值为空。违反非空约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用:postgres(PostgreSQL)9.4.5

Using: postgres (PostgreSQL) 9.4.5

我刚刚将 sqlite3 数据库迁移到了 postgresql 数据库。由于这种迁移,由于某种原因,当我尝试创建用户时,引发了关于 user_id (这是主键)的错误。 sqlite3 以前不是问题。我花了一些时间查看文档和堆栈问题,但仍然感到困惑。

I just migrated a sqlite3 db onto a postgresql db. For some reason since this migration, when I try to create a user, an error regarding the user_id (which is a primary key) is being raised. This was not an issue before with sqlite3. I have spent time looking through the docs and stack questions, but remain confused.

内部 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:

pyramid 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:

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: '


推荐答案

首先。

  我将ID命名约定从数据库中的 user_id 更改为简单的 id (其他所有情况都如此)。

First.
   I changed the id naming convention from user_id to simply id in the database (this is true for all others).

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)

第二。

  在将原始sqlite db文件转储到postgres中(从sqlite3-> postgres)而不是在postgres中创建数据库时发现了问题。

  因此,我在SQLAlchemy中运行了原始代码,但是这次指向了postgres db:

Second.
   The issue was found in dumping the original sqlite db file into postgres (from sqlite3 --> postgres) instead of creating the db in postgres.
   So, I ran the original code in SQLAlchemy, but this time pointing to the postgres db:

engine = create_engine('postgresql://localhost/some_db')

这创建了所需的关系和序列(通过<$ c $显示c> \ds 在postgres中, psql )。问题已解决。

This created the needed relationships and sequences (shown via \ds in postgres, psql). Issue resolved.

这篇关于IntegrityError:错误:列“ user_id”中的值为空。违反非空约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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