烧瓶Flask-SQLAlchemy datetime utcnow

时间:2015-09-21 03:39:08

标签: datetime flask flask-sqlalchemy

我想创建一个博客网络应用,但是当db.session.commit()提交评论时,它会更改表time中的posts字段。我真正想要做的是,帖子的时间是帖子提交的时间,它不会随着评论的提交而改变。 这是我的代码:

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,它都会更改相应的帖子,db.session.commit()更改,这将导致Post.time的更改。我该如何避免这种变化?

任何帮助将不胜感激!非常感谢!!

1 个答案:

答案 0 :(得分:0)

Web应用程序的问题不是来自于烧瓶部分,而是来自mysql部分: mysql中Post的时间字段被定义为“on update”,为了解决这个问题,您可以使用以下命令更改列:

ALTER TABLE posts CHANGE `time` `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP;

现在,当您在帖子中执行show columns时;在mysql中,它将不再显示“on update”。

我从How do I alter a mysql table column defaults?https://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html得到了答案 谢谢你们,无论如何!!