我想创建一个博客web应用程序,但是当db.session.commit()提交评论时,它将更改表posts中的time字段。我真正想做的是,发布的时间是当帖子被提交的时候,它不会随着评论的提交而改变。这是我的代码:
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)每次post.num_of_comments加1,它就会更改相应的post,并更改db.session.commit(),这将导致Post.time的更改。我该如何避免这种变化?
任何帮助都将不胜感激!非常感谢!!
发布于 2015-09-23 12:44:39
web应用程序的问题不是来自于烧瓶部分,而是来自mysql部分: mysql中Post的时间域被定义为"on“,要解决这个问题,您可以使用:
ALTER TABLE posts CHANGE `time` `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;现在,当您在posts中执行显示列时;在mysql中,它将不再显示"on“。
我从How do I alter a mysql table column defaults?和https://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html那里得到了答案,不管怎样,谢谢你们!
https://stackoverflow.com/questions/32686986
复制相似问题