I have recently started working with database. I am trying to set up a model using SQLalchemy. The models.py and database.py are shown as below:
#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
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. I think the problem occurs somewhere between SQLite3 and sqlalchemy when assigning the primary key... I don't know neither well. Please help this poor noobie, thanks!
flask-sqlalchemyover the standard SQLAlcehmy: flask-sqlalchemy.pocoo.org/2.1/quickstartautoincrement, did you delete the database file and create it again?create_alldoesn't perform migrations.