Assign a parent to an existing entity

一笑奈何 提交于 2020-01-06 08:25:19

问题


I have a datastore which is already populated with entities. However, they haven't been arranged into entity groups (a.k.a parent-child relationships). My entity Kinds are:

team = Team.get_by_key_name('Plants')
query = Plants.all()

The plants haven't been assigned to the Plants team yet:

query = Plants.all().ancestor(team)
plants = query.fetch(50)
# This will result in an empty list

I would like to assign them to the team now:

query = Plants.all()
plants = query.fetch(50)

for p in plants:
  # This isn't right
  p.parent = team

db.put(plants)

When I try to query again based on ancestor:

query = Plants.all().ancestor(team)
plants = query.fetch(50)
# This still results in an empty list

Question: How do I assign a parent to an already existing entity?


回答1:


In my experience the easiest way to do this is to create a new entity copied with all the exact same info, and set the parent appropriately on this new entity.

This is because the parent becomes part of an entity's key (hence why you need to pass any existing parent to db.Key, or get_by_key_name, etc for them to work properly), so it's not changeable in the way you describe (or at least, not as far as I know).

Edit: Xion brings up a good point that I forgot to mention. When replacing the previous object with the new one, you also have to take care of any ReferenceProperty and ListProperty(db.Key) that may have pointed to the old object. I guess the lesson of the day here is to design and think about entity groups more carefully before putting down any data.



来源:https://stackoverflow.com/questions/6832575/assign-a-parent-to-an-existing-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!