[英]NOT NULL constraint failed for SQLachemy model
I have recently started working with database. 我最近开始使用数据库。 I am trying to set up a model using SQLalchemy.
我正在尝试使用SQLalchemy建立模型。 The models.py and database.py are shown as below:
models.py和database.py如下所示:
#models.py
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Expense(Base):
__tablename__ = 'expense'
id = sa.Column(sa.BigInteger, primary_key=True)
username = sa.Column(
sa.String,
info={'label': 'Name'},
nullable=False
)
def __init__(self, username):
self.username = username
def __repr__(self):
return '<User %r>' % (self.username)
and 和
#database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base, Expense
def init_db():
engine = create_engine('sqlite:///test.db')
Base.metadata.create_all(engine)
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
new_entry = Expense(username="noobie")
session.add(new_entry)
session.commit()
init_db()
I am running these on python3, and when I run database.py, I get 我在python3上运行它们,当我运行database.py时,我得到
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: expense.id [SQL: 'INSERT INTO expense (username) VALUES (?)'] [parameters: ('noobie',)]
One response here suggests that using sqlite_autoincrement=True
will solve the problem, but it didn't work on mine. 这里的一个响应表明,使用
sqlite_autoincrement=True
可以解决问题,但不适用于我的问题。 I think the problem occurs somewhere between SQLite3 and sqlalchemy when assigning the primary key... I don't know neither well. 我认为分配主键时问题出现在SQLite3和sqlalchemy之间。我也不是很清楚。 Please help this poor noobie, thanks!
请帮助这个可怜的孩子,谢谢!
I think the reason may be BIGINT
is not allowed an primary key with autoincrement in sqlite. 我认为原因可能是
BIGINT
在sqlite中不允许自动递增的主键。 see this: Does BIGINT auto increment work for SQLAlchemy with sqlite? 看到以下内容: BIGINT自动递增是否适用于带有sqlite的SQLAlchemy?
I haven't much experience in sqlite3,but in postgresql you should use autoincrement=True
with your pkey column. 我在sqlite3中没有太多经验,但是在postgresql中,应该在pkey列中使用
autoincrement=True
。
So, try to implement this with id column like this: 因此,尝试使用id列来实现此目标,如下所示:
id = sa.Column(sa.BigInteger, primary_key=True, autoincrement=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.