0
votes

I want to define a custom string as an ID so I created the following Model:

class WikiPage(ndb.Model):
    id = ndb.StringProperty(required=True, indexed=True)
    content = ndb.TextProperty(required=True)
    history = ndb.DateTimeProperty(repeated=True)

Based on this SO thread, I believe this is right.

Now I try to query by this id by:

entity = WikiPage.get_by_id(page) # page is an existing string id, passed in as an arg

This is based on the NDB API.

This however isn't returning anything -- entity is None. It only works when I run the following query instead:

entity = WikiPage.query(WikiPage.id == page).get()

Am I defining my custom key incorrectly or misusing get_by_id() somehow?

1
Hmm, looking at the Datastore, it looks like I haven't defined the id/key correctly. The unique constraint isn't being enforced.bobbyjoe93
You have used the id field as a stringproperty. Rename it and also use this new field it for the id of your model.voscausa
@voscausa Sorry, but could you elaborate a little further?bobbyjoe93
id is special and part of the ndb.Key, See example below.voscausa

1 Answers

2
votes

Example:

class WikiPage(ndb.Model):
    your_id = ndb.StringProperty(required=True)
    content = ndb.TextProperty(required=True)
    history = ndb.DateTimeProperty(repeated=True)

entity = WikiPage(id='hello', your_id='hello', content=...., history=.....)
entity.put()

entity = WikiPage.get_by_id('hello')

or

key = ndb.Key('WikiPage','hello')
entity = key.get()
entity = WikiPage.get_by_id(key.id())

and this still works:

entity = WikiPage.query(WikiPage.your_id == 'hello').get()