I am making an inventory database using SQLalchemy, but have some struggles with it. My code looks like this:
@cross_origin
@app.route('/api/add_item_loan', methods=['POST'])
def add_item_loan():
data = request.get_json()
item = Item.query.filter_by(description=data['description']).first()
iid = item.iid
itemLoan = ItemUse(iid=iid, quantity=int(data['quantity']))
db.session.add(itemLoan)
db.session.commit()
return {'message': 'Loan added succesfully'}, 201
and my models.py looks like this:
class Item(db.Model):
__tablename__ = 'items'
iid = db.Column(db.Integer, primary_key=True)
description = db.Column(db.Text, nullable=False)
quantity = db.Column(db.Integer, nullable=False)
class ItemUse(db.Model):
__tablename__ = 'item_usage'
iuid = db.Column(db.Integer, primary_key=True)
iid = db.Column(db.Integer, db.ForeignKey('items.iid'), nullable=False)
quantity = db.Column(db.Integer, nullable=False)
start_date = db.Column(db.DateTime, default=date.today())
end_date = db.Column(db.DateTime, nullable=True)
and when I try to add an item, I get this error:
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: item_usage.iuid
[SQL: INSERT INTO item_usage (iid, quantity, start_date, end_date) VALUES (?, ?, ?, ?)]
[parameters: (1, 2, '2025-10-17 00:00:00.000000', None)]
(Background on this error at: https://sqlalche.me/e/20/gkpj)
I have searched a little here, and tried quite some things, but nothing seems to work.
The database is sqlite, and I use flask migrate.
Edit: I had to delete my migrations folder and my database, and now everything is working, solved
iuidfield after it was first created?.schema item_usage. This will give the actual schema of your table.