SQLAlchemy不可为空的外键约束违规

时间:2018-10-31 11:10:14

标签: python sqlite sqlalchemy foreign-keys

我的数据库配置存在问题,因为ForeignKey约束被配置为不为null,但是发生了父删除事件,使ForeignKey指向了不存在的id。这是一个最小的示例,它不生成IntegrityError。当然,我需要它来在最终提交时生成错误。

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
app = Flask(__name__)
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////INSERT_PATH_HERE/data-test-scratch.sqlite'
db.init_app(app)
app.app_context().push()

class User(db.Model):
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)

class Attachment(db.Model):
    __tablename__ = 'attachment'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    user = db.relationship('User', uselist=False)

db.drop_all()
db.create_all()

user = User()
db.session.add(user)
db.session.flush()
attachment = Attachment(user_id=user.id)
db.session.add(attachment)
db.session.commit()
db.session.delete(user)
db.session.commit()
print(attachment.user, attachment.user_id) # (None, 1)

请注意,我正在SQLlite中进行开发测试,但是产品将是Postgres,我想知道这两种配置在默认行为上是否存在差异?

0 个答案:

没有答案