Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

app engine ndb - how to load entity by key using id?

I am trying to load an entity by key using the id it was assigned by the datastore but I don't see any api method to do this (using NDB). I thought I would be able to make a Key from an integer id and use key.get() to load the entity, but I don't see a way to make a key from just an id. I suspect I am missing something obvious here. How should I load an entity where I only know the id of it?

like image 877
user605331 Avatar asked Apr 05 '12 12:04

user605331


3 Answers

Another way: ndb.Key(YourModel, id).get().

like image 196
Guido van Rossum Avatar answered Nov 12 '22 21:11

Guido van Rossum


YourModel.get_by_id() gets a model instance by id.

here the docs:
https://developers.google.com/appengine/docs/python/ndb/modelclass#Model_get_by_id

don't think you can't get an entity by id without knowing the kind because instances of different Model classes can have the same id/key_name

like image 28
aschmid00 Avatar answered Nov 12 '22 21:11

aschmid00


Models in NDB don't define their key type as part of the model. This is nifty in that you can have one given model type that is accessible through multiple different kinds of keys and parents, which makes them more flexible. But it's somewhat problematic because it isn't always clear what the key represents or where it comes from.

So in cases where there's only ever one kind of key for a given model (which is almost every model), I like to create a class method for generating that key, which adds a bit of semantic clarity:

class Book(ndb.Model):
  title = ndb.StringProperty()
  pages = ndb.IntegerProperty()
  @classmethod
  def make_key(cls, isbn):
    return ndb.Key(cls, isbn)

b = Book.make_key('1234-5678').get()

Sure the added code is not strictly necessary, but it adds clarity and makes my models more long-term maintainable.

like image 2
tylerl Avatar answered Nov 12 '22 19:11

tylerl