gpt4 book ai didi

python-3.x - 在 Flask SQLAlchemy 中插入新值之前,如何强制检查外键?

转载 作者:行者123 更新时间:2023-12-04 15:57:40 24 4
gpt4 key购买 nike

我正在 Flask-SQLAlchemy 中构建以下数据库方案:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

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

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
posts = db.relationship('Post', backref='author', lazy='dynamic')

def __repr__(self):
return '<User {}>'.format(self.username)

class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

def __repr__(self):
return '<Post {}>'.format(self.body)

db.drop_all()
db.create_all()

u = User(username='susan', email='susan@example.com')
db.session.add(u)

p = Post(body='this is my first post!', user_id=1)

db.session.add(p)

# Now I create a new post for a non-existing user and I'd expect an error...
p = Post(body='this is my second post!', user_id=2)
db.session.add(p)
db.session.commit()

如您所见,我手动输入了一个新用户,然后输入了两个帖子。

我希望在第二篇文章插入时抛出错误,因为 user_id=2 不存在于数据库中。

但是插入成功了,我也看到了数据库中的数据:
sqlite> select * from post;
1|this is my post!|2018-07-09 16:13:16.947856|1
2|this is my post!|2018-07-09 16:13:16.948996|2
sqlite>

如何强制执行约束以使其抛出错误?

谢谢你的帮助。

最佳答案

要解决这种情况,与其为 post 对象分配一个 id,不如将 User 与 Post 关联起来,这样更好,更像 ORM。此外,通过强制执行 NOT NULL外键列的能力,不能添加无效数字。

例如:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime

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

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
posts = db.relationship('Post', lazy='dynamic', back_populates='author')

def __repr__(self):
return '<User {}>'.format(self.username)

class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
author = db.relationship('User')

def __repr__(self):
return '<Post {}>'.format(self.body)

db.drop_all()
db.create_all()

# Susan will be both created and added to the session
u1 = User(username='susan', email='susan@example.com')
db.session.add(u1)

# John will be created, but not added
u2 = User(username='john', email='john@example.com')

# Create a post by Susan
p1 = Post(body='this is my post!', author=u1)

# Add susan's post to the session
db.session.add(p1)

# Create a post by john, since john does not yet exist as a user, he is created automatically
p2 = Post(body='this is my post!', author=u2)

# Add john's post to the session
db.session.add(p2)

# After the session has everything defined, commit it to the database
db.session.commit()

关于python-3.x - 在 Flask SQLAlchemy 中插入新值之前,如何强制检查外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51246354/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com