ndb retrieving entity key by ID without parent

£可爱£侵袭症+ 提交于 2019-12-04 04:59:46

I ran into this problem too. I think you do have the solution.

The better solution would be to stop using IDs to reference entities, and store either the actual key or a full path.

Internally, I use keys instead of IDs.

On my rest API, I used to do http://url/kind/id (where id looked like "123") to fetch an entity. I modified that to provide the complete ancestor path to the entity: http://url/kind/ancestor-ancestor-id (789-456-123), I'd then parse that string, generate a key, and then get by key.

Since you have full information about your ancestor and you know your id, you could directly create your key and get the entity, as follows:

my_key = ndb.Key(Ancestor, ancestor.key.id(), SomeModel, id)
entity = my_key.get()

This way you avoid making a query that costs more than a get operation both in terms of money and speed.

Hope this helps.

I want to make a little addition to dargonx's answer.

In my application on front-end I use string representation of keys:

str(instance.key())

When I need to make some changes with instence even if it is a descendant I use only string representation of its key. For example I have key_str -- argument from request to delete instance':

instance = Kind.get(key_str)
instance.delete()

My solution is using urlsafe to get item without worry about parent id:

pk = ndb.Key(Product, 1234)
usafe = LocationItem.get_by_id(5678, parent=pk).key.urlsafe()
# now can get by urlsafe
item = ndb.Key(urlsafe=usafe)
print item
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!