在peewee中是否有一个类似MySQL中TimeStamp的DateTimeField自动更新选项?

ubof19bj  于 2023-01-25  发布在  Mysql
关注(0)|答案(4)|浏览(109)

我想一个时间戳字段更新记录每次被修改一样,在MySQL。
DateTimeField(default=datetime.datetime.now())只会在第一次创建时设置它...
有没有简单的解决方案?唯一的解决方案是手动设置mysqdb中的列选项?

5cg8jx4n

5cg8jx4n1#

您可以重写模型类上的save方法。

class Something(Model):
    created = DateTimeField(default=datetime.datetime.now)
    modified = DateTimeField

    def save(self, *args, **kwargs):
        self.modified = datetime.datetime.now()
        return super(Something, self).save(*args, **kwargs)
kmb7vmvb

kmb7vmvb2#

只要在MySQL中使用TIMESTAMP类型即可。每当行更新时,此字段将自动更新。
model

last_updated = peewee.TimestampField()
omjgkv6w

omjgkv6w3#

你也可以重写update方法来提供。就像coleifer所做的那样:

class Something(Model):
    created = DateTimeField(default=datetime.datetime.now)
    modified = DateTimeField

    @classmethod
    def update(cls, *args, **kwargs):
        kwargs['modified'] = datetime.datetime.now()
        return super(Something, cls).save(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.modified = datetime.datetime.now()
        return super(Something, self).save(*args, **kwargs)

也可以对replace方法执行相同的操作

waxmsbnn

waxmsbnn4#

from datetime import datetime

from peewee import (AutoField, CharField, DateTimeField, FloatField,
                    IntegerField, Model, MySQLDatabase, TextField, SQL)

from config import DataBaseConfig

mysql_client = MySQLDatabase(
    "your_database_name",
    host=DataBaseConfig.host,
    port=DataBaseConfig.port,
    user=DataBaseConfig.user,
    password=DataBaseConfig.password,
)

class CommonModel(Model):
    id = AutoField(verbose_name="primary key")
    create_time = DateTimeField(default=datetime.now, verbose_name="create time")
    update_time = DateTimeField(default=datetime.now, verbose_name="update time", constraints=[SQL('ON UPDATE CURRENT_TIMESTAMP')])

    class Meta:
        database = mysql_client

可以参考此文档,单列索引和约束!

相关问题