[PYTHON] Flask-How to enforce SQLAlchemy foreign key constraints

I was looking for a way to get an error when I violated a foreign key constraint. Conclusion: (not found). Give up and protect on the code side.

Method of verification

environment

Python 3.7  Flask-SQLAlchemy v2.4.1

Create two tables.

Model.py


from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), nullable=False)
    addresses = db.relationship('Address', backref='person', lazy=True)


class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(120), nullable=False)
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'),
                                nullable=False)

https://flask-sqlalchemy.palletsprojects.com/en/2.x/quickstart/ From https://flask-sqlalchemy.palletsprojects.com/en/2.x/models/

The finished table

test.db


CREATE TABLE "person" (
	"id"	INTEGER NOT NULL,
	"name"	VARCHAR(50) NOT NULL,
	PRIMARY KEY("id")
);

CREATE TABLE "address" (
	"id"	INTEGER NOT NULL,
	"email"	VARCHAR(120) NOT NULL,
	"person_id"	INTEGER NOT NULL,
	PRIMARY KEY("id"),
	FOREIGN KEY("person_id") REFERENCES "person"("id")
);

Do a test

test.py


import unittest

def testForeignKey(self):
    db.create_all()
    db.session.add(db.Address(id=0, email="aaa", person_id="bbb"))
    db.session.commit()
    
    
if __name__ == '__main__':
    unittest.main()

Look in test.db to see if a new record has been added.

If anyone knows how to get an error without changing the test, please let me know.

Recommended Posts

Flask-How to enforce SQLAlchemy foreign key constraints
Write foreign key constraints in Django