Python sqlalchemy.exc.IntegrityError
我不明白为什么会发生这种错误。 数据库的代码如下:Python sqlalchemy.exc.IntegrityError,python,sqlalchemy,Python,Sqlalchemy,我不明白为什么会发生这种错误。 数据库的代码如下: 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',
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), nullable=False,
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, nullable=False, default=datetime.utcnow)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f'{self.title}'
我应该更改什么才能使其工作。我应该提到,我过去使用过相同的代码,并且它工作了基于您的模型,需要字段user\u id,因为参数为nullable=False
您必须填写此字段和其他必填字段,这些字段的可选字段也有nullable=False或set 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\u id=db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)
@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')