简体   繁体   English

Flask SQLAlchemy updated_on

[英]Flask SQLAlchemy updated_on

I want to create field Datetime which will update current date time when a row updated.我想创建字段Datetime ,它将在更新行时更新当前日期时间。 I tried this:我试过这个:

updated_on = Column(DateTime, onupdate=db.func.now())

and this:和这个:

updated_on = Column(DateTime, server_onupdate=db.func.now())

But a field is update only when I add a new row and no changes after update this row.但是只有当我添加新行并且更新该行后没有更改时才会更新字段。 upd:更新:

class UserLog(db.Model):
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('user.id'))
    state = Column(String(25))
    created_on = Column(DateTime, server_default=db.func.now())
    updated_on = Column(DateTime, onupdate=datetime.utcnow)

First of all, server_onupdate does not do anything server-side, and it's only there so that SQLAlchemy knows the server is 'supposed to' generate a value upon update.首先, server_onupdate不会在服务器端做任何事情,它只是在那里让 SQLAlchemy 知道服务器“应该”在更新时生成一个值。 It's really misleading.这真的是误导。 You have to manually configure your database to generate the value upon update.您必须手动配置数据库以在更新时生成值。 SQLAlchemy doesn't do it for you. SQLAlchemy 不适合你。

So use onupdate .所以使用onupdate onupdate=datetime.utcnow . onupdate=datetime.utcnow Don't forget to import datetime .不要忘记导入datetime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM