Reputation:
I edited my table by adding the column "post_id" to define the relationship between posts and replies (I'm trying to add comments to my flask application). So now when ever I run my site I get the error:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) table reply has no column named post_id [SQL: 'INSERT INTO reply (title, date_posted, content, user_id, post_id) VALUES (?, ?, ?, ?, ?)'] [parameters: ('testtitle', '2020-12-15 04:52:48.159734', 'testcontent', 5, None)]
so I try to update it by inserting the line:
reply.__table__.update(reply)
but then I get the error
sqlalchemy.exc.ArgumentError: SQL expression object or string expected, got object of type <class 'flask_sqlalchemy.model.DefaultMeta'> instead
My code for reference (please tell me if there is anything wrong with it I am very new to flask and SQLalchemy):
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
replys = db.relationship('Reply', backref='post', lazy=True)
def get_replys(self):
return Reply.query.filter_by(post_id=Post.id).order_by(Reply.timestamp.desc())
def __repr__(self):
return f"Post('{self.title}', '{self.date_posted}')"
class Reply(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
post_id = db.Column(db.Integer, db.ForeignKey('post.id'), nullable=False)
def __repr__(self):
return f"Reply('{self.title}', '{self.date_posted}')"
routes.py
@app.route("/post/reply", methods=['GET', 'POST'])
@login_required
def new_reply():
form = ReplyForm()
if form.validate_on_submit():
reply = Reply(title=form.title.data, content=form.content.data, author=current_user,)
db.session.add(reply)
db.session.commit()
flash('reply posted', 'success')
return redirect(url_for('home'))
return render_template('Reply.html', title='New Reply', form=form, legend='New Reply',)
Upvotes: 2
Views: 98
Reputation: 621
After adding a new column, you need to add migrations. Migration is the process of applying your code changes to the database. In Flask a nice package if flask-migrate which is Alembic wrapped for Flask. You configure it like:
migrate.init_app(app, db)
The commands are, after configuring flask:
$ flask db init # first time
$ flask db migrate
$ flask db upgrade
Try the package!
Upvotes: 1