0

I have below table schema defined in sqlalchemy where user_id is foreign key referencing to User's user_id table

class Manufacturer(Model):
__tablename__='Manufacturer'
Manufacturer_id=Column(Integer,primary_key=True,autoincrement=True)
name=Column(String(length=100),nullable=False)
description=Column(String(length=1000),nullable=False)
user_id=Column(Integer,ForeignKey(User.user_id),nullable=False)

but when table is created in sqllite db foreign key not added to table and entry is getting inserted even though user table does not have value for userid

i searched for this issue and found in order to solve this problem we need to set PRAGMA foreign_keys = ON;
but i am not able to figure it out how this can be done with my current configuration for DB

i have below code to create engine and to add record with SQL Configuration for engine :-

engine=create_engine(SQLALCHEMY_DATABASE_URI) _Session=orm.sessionmaker(autocommit=False,autoflush=True,bind=engine) session=orm.scoped_session(_Session)

code to add entry in table

 man_details=Manufacturer(**param)
    session.add(man_details)
    session.commit()

Please suggest how i can set foreign key constraint from python-Flask-SQLAlchemy for tables created in SQLlite3

PythonUser
  • 706
  • 4
  • 15

1 Answers1

0

below code worked for me and found it from below link -

Sqlite / SQLAlchemy: how to enforce Foreign Keys?

   def _fk_pragma_on_connect(dbapi_con, con_record):
    dbapi_con.execute('pragma foreign_keys=ON')

from sqlalchemy import event
event.listen(engine, 'connect', _fk_pragma_on_connect)
Community
  • 1
  • 1
PythonUser
  • 706
  • 4
  • 15