postgresql 如何自动填充 SQLAlchemy 数据库字段?(Flask-SQLAlchemy)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12154129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 00:14:10  来源:igfitidea点击:

How Can I Automatically Populate SQLAlchemy Database Fields? (Flask-SQLAlchemy)

databasepostgresqlsqlalchemyflaskflask-sqlalchemy

提问by rdegges

I've got a simple User model, defined like so:

我有一个简单的 User 模型,定义如下:

# models.py
from datetime import datetime
from myapp import db

class User(db.Model):
  id = db.Column(db.Integer(), primary_key=True)
  email = db.Column(db.String(100), unique=True)
  password = db.Column(db.String(100))
  date_updated = db.Column(db.DateTime())

  def __init__(self, email, password, date_updated=None):
    self.email = email
    self.password = password
    self.date_updated = datetime.utcnow()

When I create a new User object, my date_updatedfield gets set to the current time. What I'd like to do is make it so that wheneverI save changes to my User object my date_updatedfield is set to the current time automatically.

当我创建一个新的 User 对象时,我的date_updated字段被设置为当前时间。我想要做的是,每当我保存对用户对象的更改时,我的date_updated字段都会自动设置为当前时间。

I've scoured the documentation, but for the life of me I can't seem to find any references to this. I'm very new to SQLAlchemy, so I really have no prior experience to draw from.

我已经搜索了文档,但是对于我的一生,我似乎找不到任何对此的引用。我对 SQLAlchemy 很陌生,所以我真的没有经验可以借鉴。

Would love some feedback, thank you.

希望得到一些反馈,谢谢。

回答by plaes

Just add server_defaultor defaultargument to the column fields:

只需向列字段添加server_defaultdefault参数:

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

I prefer the {created,updated}_oncolumn names. ;)

我更喜欢{created,updated}_on列名。;)

SQLAlchemy docs about column insert/update defaults.

SQLAlchemy 文档关于列插入/更新默认值

[Edit]:Updated code to use server_defaultarguments in the code.

[编辑]:更新了代码以server_default在代码中使用参数。

[Edit 2]:Replaced onupdatewith server_onupdatearguments.

[编辑 2]:替换onupdateserver_onupdate参数。

回答by Savad KP

date_created  = db.Column(db.DateTime,  default=db.func.current_timestamp())
date_modified = db.Column(db.DateTime,  default=db.func.current_timestamp(),
                                       onupdate=db.func.current_timestamp())