How to delete an entity including all children

2019-02-24 12:04发布

问题:

I would like to do a cascading delete on an entity in the datastore. By this I mean all children and indirect children will also be deleted. I initially assumed this would be default behavior but somehow it is not...

My thought was something like this:

ndb.delete_multi(ndb.Model.query(ancestor=key).iter(keys_only = True))

But the Model should be a wildcard, because the entity can be the parent of several classes...

I would also like to delete BlobKeyProperties when deleting an entity. For this I was thinking about:

@classmethod
  def _post_delete_hook(cls, key, future):
  # inform someone they have lost a friend

which I should maybe use for cascading delete as well?

回答1:

For kindless ancestor queries create the query from the query class

ndb.delete_multi(ndb.Query(ancestor=key).iter(keys_only = True))

I wouldn't use the cascading delete for all child entities. If you have a lot then it will be much slower (unless you want to run the delete in a task).