我只想在创建新对象时更新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发布于 2022-08-03 03:15:27
最好的方法是重写对象类的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)我们只需要将一个操作附加到操作列表中,询问时间戳更新。然后调用父级的更新方法。现在,您可以忘记时间戳,并按照需要使用update方法。
item = SalesItem.get('pynamodb-test')
# do your updates here
item.update(actions=[
SalesItem.sales.set(item.sales + 1)
])https://stackoverflow.com/questions/68752783
复制相似问题