使用 Pynamodb 保存对象创建日期时间

问题描述 投票:0回答:1

我想仅在创建新对象时更新

creation_datetime
,并在使用
last_update_datetime
方法时在每次更新时更新
save
。即使现有对象正在更新,
default_for_new
也是更新时间。有什么替代方案吗?

下面是我尝试过的示例代码

from pynamodb.models import Model
from pynamodb.attributes import  UTCDateTimeAttribute

def current_datetime():
    from datetime import datetime
    return datetime.now()


class AbstractDateTimeModel(Model):
    creation_datetime = UTCDateTimeAttribute(default_for_new=current_datetime)
    last_update_datetime = UTCDateTimeAttribute(default=current_datetime)

    class Meta(object):
        abstract = True
amazon-dynamodb pynamodb
1个回答
2
投票

对于版本< 6.0.0

执行此操作的最佳方法是重写 Object 类的 update 方法。这是一个例子:

from datetime import datetime, timezone

from pynamodb.models import Model
from pynamodb.settings import OperationSettings
from pynamodb.attributes import UTCDateTimeAttribute, UnicodeAttribute, NumberAttribute


def get_current_time_utc():
        return datetime.now(timezone.utc)


class SalesItem(Model):
    class Meta:
        table_name = 'monthlySales'

    id = UnicodeAttribute(hash_key=True)
    month= UnicodeAttribute()
    sales= NumberAttribute()
    createDateTime = UTCDateTimeAttribute(default_for_new=get_current_time_utc)
    updateDateTime = UTCDateTimeAttribute(default_for_new=get_current_time_utc)


    # overriding the method to add timestamp on update
    def update(self, actions=[], condition=None, settings=OperationSettings.default):
        actions.append(SalesItem.updateDateTime.set(get_current_time_utc()))
        Model.update(self, actions, condition, settings)

我们只需要将一个操作附加到操作列表中,询问时间戳更新即可。然后调用父级的更新方法。现在您可以忘记时间戳并像您一样使用更新方法。

item = SalesItem.get('pynamodb-test')
# do your updates here
item.update(actions=[
    SalesItem.sales.set(item.sales + 1)
])

适用于 v6.0.0

根据发行说明

OperationSettings
已被删除,因此覆盖功能将是:

# overriding the method to add timestamp on update
def update(self, actions=[], condition=None):
    actions.append(SalesItem.updateDateTime.set(get_current_time_utc()))
    Model.update(self, actions, condition)
© www.soinside.com 2019 - 2024. All rights reserved.