I am wanting to delete old entities from ndb. The entities have a ndb.DateTimeProperty(auto_now_add=True) property called date:
我想从ndb中删除旧实体。实体有一个名为date的ndb.DateTimeProperty(auto_now_add = True)属性:
class Mjcode(ndb.Model):
code = ndb.StringProperty()
ifv = ndb.StringProperty()
date = ndb.DateTimeProperty(auto_now_add=True)
This is how far I've come:
这是我走了多远:
mjcode_keys = Mjcode.query().fetch(keys_only=True)
countOfMjcodes = len(mjcode_keys)
self.response.write('Mjcode - found entity count: ' + str(countOfMjcodes) + '<br/>')
if countOfMjcodes > 0:
self.response.write('Deleting...<br/>')
ndb.delete_multi(mjcode_keys)
else:
self.response.write('No delete needed.<br/>')
This deletes the entities, but at this point it deletes all of them. What is the syntax I should enter - I suppose inside of query()? Let's say I want to purge all entities older than X number of seconds.
这将删除实体,但此时会删除所有实体。我应该输入什么语法 - 我想在query()里面?假设我要清除所有早于X秒的实体。
1 个解决方案
#1
7
You can filter queries like this:
您可以像这样过滤查询:
import datetime
earliest = datetime.datetime.now() - datetime.timedelta(days=7)
Mjcode.query(Mjcode.date <= earliest).fetch(keys_only=True)
This will remove any entities older than 7 days. You can edit the datetime.timedelta to change the time after which entities are removed.
这将删除任何超过7天的实体。您可以编辑datetime.timedelta以更改删除实体的时间。
#1
7
You can filter queries like this:
您可以像这样过滤查询:
import datetime
earliest = datetime.datetime.now() - datetime.timedelta(days=7)
Mjcode.query(Mjcode.date <= earliest).fetch(keys_only=True)
This will remove any entities older than 7 days. You can edit the datetime.timedelta to change the time after which entities are removed.
这将删除任何超过7天的实体。您可以编辑datetime.timedelta以更改删除实体的时间。