我想仅在创建新对象时更新creation_datetime
,并在使用save
方法的每次更新时更新last_update_datetime
。即使现有对象正在更新,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
最好的方法是重写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)
])