I would like to create a blog web app, but when comments were committed by db.session.commit()
, it will change the time
field in table posts
. what I really want to do is, time of post is when the post was committed, it won't change with commits of comments.
Here is my code:
class Post(db.Model):
__tablename__ = 'posts'
id = db.Column(db.Integer, primary_key=True, nullable=False)
time = db.Column(db.DateTime, index=True, nullable=False, default=datetime.utcnow)
text = db.Column(db.Text, nullable=False)
num_of_comments = db.Column(db.Integer, index=True, default=0)
comments = db.relationship('Comment', backref='post', lazy='dynamic')
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))
text = db.Column(db.Text)
@main.route('/post/<int:id>', methods=['GET', 'POST'])
def post(id):
post = Post.query.get_or_404(id)
form = CommentForm()
if form.validate_on_submit():
comment_author = current_user._get_current_object()
comment = Comment(text = form.text.data
post=post,
author=comment_author)
db.session.add(comment)
if post.num_of_comments == None:
post.num_of_comments = 0
post.num_of_comments += 1
flash('Your comment has been submitted.')
return redirect(url_for('.post', id=post.id))
comments = post.comments.order_by(Comment.timestamp.desc())
return render_template('post.html', posts=[post], form=form, comments=comments)
each time post.num_of_comments
add by 1, it will change the corresponding post, and db.session.commit()
the change, and this will cause the change of Post.time
. How should I avoid the change?
Any help will be appreciated!! Thanks very much!!