0
votes

When creating a new entity of class Example(ndb.Model) I can set the parent as follows:

e1 = Example(parent=some_entity.key)
e1.put()

This gets saved in the Datastore and everything works.

I can just as well set the id:

e2 = Example(id='some_unique_id')
e2.put()

But when I try to set both the id and the parent of an entity it seems the parent is not getting set:

e3 = Example(parent=some_entity.key, id="some_other_unique_id")
e3.put()

Also, the above seems to allow me to save the e3 without an issue, however I am no longer able to get it via it's id. The following doesn't work:

Example.get_by_id("some_other_unique_id")

returns None.

Is there any way I could both set the parent and an id on an entity? I tried building a key with the ancestor path using ndb.Key() but to no avail.

1
Only the id is not enough. You also have to use the ancestor like: ndb.Key('Example', 'some_other_unique_id', parent=some_entity.key).get()voscausa

1 Answers

5
votes

You also need to add a parent parameter: https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_get_by_id

Explanation: above method is a shorthand for Key(cls, id).get(). Key is what uniquely identifies an entity in Datastore, not id. Key consists of: app name (implicit, cannot be set via API), namespace (optional), kind, parent key (optional) and id. You need all those to create a unique key.