Gianni Di Noia
Gianni Di Noia

Reputation: 1578

get_by_id and parent Key

I ever use get_by_id for get an entity from datastore and never use Ancestor Paths. But the complexity of my models has made it necessary. In fact Ancestor Paths solve a big problem but now when I try to get_by_id an entity return None if the entity have the parent key. This means that I need to add the parent Key:

entity = MyModel.get_by_id(id)

This would becomes:

entity = MyModel.get_by_id(id, parent=key)

How to build the parent Key?

edit:

At this point I prefer to leave ancestor paths and add another keyproperty.

Upvotes: 4

Views: 2817

Answers (1)

sahid
sahid

Reputation: 2610

If you want using entity group you can simply create a key like that:

key_parent = db.Key.from_path('MyModelParent', 'id_parent') # You don't have to create this kind in the datastore.

id = int(self.request.get('id'))
entity = MyModel.get_by_id(id, parent=key_parent)

I notice that: You use an upper case for the key parameter. It's parent not Parent.

entity = MyModel.get_by_id(id, Parent=key) # Wrong
entity = MyModel.get_by_id(id, parent=key)

Oh, you are using NDB:

key_parent = ndb.Key('MyModelParent', 'id_parent')

Upvotes: 7

Related Questions