【发布时间】:2015-12-17 16:00:36
【问题描述】:
我想创建一个博客网络应用程序,但是当 cmets 由 db.session.commit() 提交时,它会更改表 posts 中的 time 字段。我真正想做的是,发布时间是提交帖子的时间,它不会随着 cmets 的提交而改变。
这是我的代码:
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的变化。我应该如何避免这种变化?
任何帮助将不胜感激!非常感谢!!
【问题讨论】:
-
你在哪里打电话
db.session.commit()? -
您是否有任何数据库触发器可能会更新posts.time?
-
每次更改后,db都会更新更改。我可以这样做:在 config.py 中添加 SQLALCHEMY_COMMIT_ON_TEARDOWN = True
-
我想保留 Post.time 帖子发布的时间,而不是帖子更改的时间。
标签: datetime flask flask-sqlalchemy