如何解决sqlalchemy.exc.IntegrityError
sqlalchemy.exc.IntegrityError: (sqlite3.IntegrityError) NOT NULL constraint failed: post.user_id
[SQL: INSERT INTO post (title,content,date_created,user_id) VALUES (?,?,?)]
[parameters: ('dsaglhfl','sijd;avbvjab','2020-08-22 09:50:09.983189',None)]
(Background on this error at: http://sqlalche.me/e/gkpj)
我不明白为什么会发生此错误。 数据库的代码如下:
class User(db.Model,UserMixin):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(20),nullable=False,unique=True)
email = db.Column(db.String(50),nullable=False)
password = db.Column(db.String(60),nullable=False)
image_file = db.Column(db.String(60),default='default.jpg')
posts = db.relationship('Post',backref='author',lazy=True)
def __repr__(self):
return f'{self.username}'
class Post(db.Model):
id = db.Column(db.Integer,primary_key=True)
title = db.Column(db.String(100),nullable=False)
content = db.Column(db.Text,nullable=False)
date_created = db.Column(
db.DateTime,default=datetime.utcnow)
user_id = db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)
def __repr__(self):
return f'{self.title}'
还有路线
@app.route('/post/new',methods=['GET','POST'])
@login_required
def new_post():
form = PostForm()
if form.validate_on_submit():
post = Post(title=form.title.data,content=form.content.data)
db.session.add(post)
db.session.commit()
flash('Your post was added!','success')
return redirect(url_for('home'))
return render_template('create_post.html',form=form,title='New Pos',heading='New Post')
我应该进行些什么更改,以便它可以工作。我应该说,我过去使用相同的代码,并且可以工作
解决方法
根据您的模型,必须输入 user_id 字段,因为参数被赋予 nullable = False 。
您必须填写此字段以及其他必填字段,其中也包含 nullable = False 或为可选字段设置 nullable = True 。
,Crazyzubr是正确的,问题在于如何实例化Post()对象:
post = Post(title=form.title.data,content=form.content.data)
db.session.add(post)
您从未在将post.user_id添加到会话之前对其进行设置,因此您将在Post模型中使NOT NULL约束失效:
user_id = db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。