开发者

Assign a parent to an existing entity

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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜