使用烧瓶炼金术在 SQLlite 中未设置外键约束 [英] Foreign key contraint is not getting set in SQLlite using flask alchemy
问题描述
我在 sqlalchemy 中定义了下表模式,其中 user_id 是引用用户的 user_id 表的外键
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)
但是当在 sqllite db 中创建表时,外键未添加到表中,即使用户表没有 userid 值,也会插入条目
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
我搜索了这个问题,发现为了解决这个问题我们需要设置PRAGMA foreign_keys = ON;
但我无法弄清楚如何使用我当前的 DB 配置来完成
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
我有以下代码来创建引擎并使用 SQL 添加记录引擎配置:-
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()
请建议我如何从 python-Flask-SQLAlchemy 为在 SQLlite3 中创建的表设置外键约束
Please suggest how i can set foreign key constraint from python-Flask-SQLAlchemy for tables created in SQLlite3
推荐答案
下面的代码对我有用,并从下面的链接找到它 -
below code worked for me and found it from below link -
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)
这篇关于使用烧瓶炼金术在 SQLlite 中未设置外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!