如何自动填充SQLAlchemy数据库字段? (Flask-SQLAlchemy) [英] How Can I Automatically Populate SQLAlchemy Database Fields? (Flask-SQLAlchemy)

查看:533
本文介绍了如何自动填充SQLAlchemy数据库字段? (Flask-SQLAlchemy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

# 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()

创建新的User对象时,我的 date_updated 字段被设置为当前时间。我想做的是使无论何时将更改保存到我的User对象时,我的 date_updated 字段都会自动设置为当前时间

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

我已经仔细阅读了文档,但是对于我一生来说,我似乎找不到任何引用。我对SQLAlchemy还是很陌生,所以我确实没有任何经验可以借鉴。

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.

很乐意提供一些反馈,谢谢。

Would love some feedback, thank you.

推荐答案

只需将 server_default default 参数添加到列字段:

Just add server_default or default argument to the column fields:

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())

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

关于列插入/更新默认值

:更新了代码以使用<$ c代码中的$ c> server_default 参数。

: Updated code to use server_default arguments in the code.

替换为带有 server_onupdate 参数的onupdate

: Replaced onupdate with server_onupdate arguments.

这篇关于如何自动填充SQLAlchemy数据库字段? (Flask-SQLAlchemy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆