1

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

4
  • Did you alter iuid field after it was first created? Commented Oct 17 at 7:19
  • 2
    Seems like you had modified iuid before now. Either changing its nullable attribute or data type or something else. If so, you could have some items in the database matching the old schema and throwing this error when you try to add a new record. Commented Oct 17 at 7:25
  • If you have sqlite3 command, can you update your question with output of this command: .schema item_usage. This will give the actual schema of your table. Commented Oct 17 at 7:33
  • i think item_usage pk iuid is Null so have a not null constraint failed it be auto increment? you also see ddl in item_usage table, because sqlite is as i know inline pk command can auto increment Commented Oct 17 at 9:07

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.