如何为多个 NDB 实体更新一个 属性?
How to update one property for multiple NDB entities?
我有 NDB 模型 class 如下所示:
class Contest(ndb.Model):
end_date = ndb.DateProperty(required=True, indexed=True)
ended = ndb.BooleanProperty(required=False, indexed=True)
...
我每天都会有一个 cron 作业来标记已通过 end_date
且 ended
等于 True
的比赛。我编写了以下代码来执行此操作:
contests = Contest.query()
current_datetime = datetime.datetime.utcnow()
today = datetime.date(current_datetime.year, current_datetime.month, current_datetime.day)
contests = contests.filter(Contest.end_date < today)
contests = contests.filter(Contest.ended == False)
contests = contests.fetch(limit=10)
for contest in contests:
contest.ended = True
ndb.put_multi(contests)
但我不喜欢它,因为我必须读取所有实体才能更新一个值。有什么办法可以修改为 keys_only
?
The object data overwrites the existing entity. The entire object is sent to Datastore
https://cloud.google.com/datastore/docs/concepts/entities#Datastore_Updating_an_entity
所以您不能只发送实体的一个字段,它会 "remove" 所有现有字段。更准确地说 - 用只有一个字段的新版本实体替换所有字段的实体。
您必须加载所有要更新的实体,包括所有属性,而不仅仅是键,设置 属性 的新值,然后放回数据库。
我认为 Python 属性 是一个很好的解决方案:
class Contest(ndb.Model):
end_date = ndb.DateProperty(required=True, indexed=True)
@property
def ended(self):
return self.end_date < date.today()
这样您就永远不需要更新您的实体。该值会在您需要时自动计算。
我有 NDB 模型 class 如下所示:
class Contest(ndb.Model):
end_date = ndb.DateProperty(required=True, indexed=True)
ended = ndb.BooleanProperty(required=False, indexed=True)
...
我每天都会有一个 cron 作业来标记已通过 end_date
且 ended
等于 True
的比赛。我编写了以下代码来执行此操作:
contests = Contest.query()
current_datetime = datetime.datetime.utcnow()
today = datetime.date(current_datetime.year, current_datetime.month, current_datetime.day)
contests = contests.filter(Contest.end_date < today)
contests = contests.filter(Contest.ended == False)
contests = contests.fetch(limit=10)
for contest in contests:
contest.ended = True
ndb.put_multi(contests)
但我不喜欢它,因为我必须读取所有实体才能更新一个值。有什么办法可以修改为 keys_only
?
The object data overwrites the existing entity. The entire object is sent to Datastore
https://cloud.google.com/datastore/docs/concepts/entities#Datastore_Updating_an_entity
所以您不能只发送实体的一个字段,它会 "remove" 所有现有字段。更准确地说 - 用只有一个字段的新版本实体替换所有字段的实体。
您必须加载所有要更新的实体,包括所有属性,而不仅仅是键,设置 属性 的新值,然后放回数据库。
我认为 Python 属性 是一个很好的解决方案:
class Contest(ndb.Model):
end_date = ndb.DateProperty(required=True, indexed=True)
@property
def ended(self):
return self.end_date < date.today()
这样您就永远不需要更新您的实体。该值会在您需要时自动计算。