vendredi 12 février 2016

Flask-SqlAlchemy Sqlite Foreign Key constraint not working?

Here is my models:

class Item(db.Model):
    id = db.Column(db.Integer, primary_key=True)

    item_type_id = db.Column(db.Integer, db.ForeignKey('item_type.id'))

    purchase_price = db.Column(db.Integer, index=True)

    purchase_transaction_id = db.Column(db.Integer, db.ForeignKey('purchase_transaction.id'))

    supplier_id = db.Column(db.Integer, db.ForeignKey('supplier.id'))

class ItemType(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    item_type = db.Column(db.String(ITEM_TYPE_LENGTH), index=True, unique=True)
    items = db.relationship('Item', backref='item_type', lazy='dynamic')

So this is what I did:

>>> db.session.add(models.Item(item_type_id=170, purchase_price=111, purchase_transaction_id=1, supplier_id=1)) 
>>> db.session.commit()

I added a new Item item_type_id is 170, but the table of item_type only has id until 20. And if I check my database, the item is successfuly added, and if I do a query like ItemType.query.get(item.item_type_id), None will be returned - which means the foreign key does not exist

I have read the docs in sqlalchemy and sqlite, they both should have foreign key constraint, I wonder why it is not working in mine

Aucun commentaire:

Enregistrer un commentaire