salyela
salyela

Reputation: 1645

Custom key for app-engine datastore entity

I want to create a simple dictionary on the datastore. So I tried created my Entity class like so

class Word(ndb.Model):
    id = ndb.KeyProperty(required=True)
    definition = ndb.StringProperty(required=True)

Where id is the actual word. The thing is when I try to add an entity, I get an error that e.g. “love” is not a key. So I changed to the following

class Word(ndb.Model):
    id = ndb.StringProperty(required=True)
    definition = ndb.StringProperty(required=True)

The problem with this new approach is that my id field isn’t viewed as the actual ID of the Entity. The data store creates my id field plus another Name/ID field. How do I use custom ID on App-Engine?

And here is how I’m adding words:

word = Word()
word.id = “love”
word.definition =“a profoundly tender, passionate affection for another person. ”
word.put()

I am hoping not to have to use this NamedModel recommendation but rather something similar to this short one, except with my structured model class.

Upvotes: 0

Views: 211

Answers (2)

Jim Morrison
Jim Morrison

Reputation: 2887

Unlike other database systems, the key for Datastore is not a user defined column. The primary key always exists as an explicit item.

From https://googleapis.dev/python/python-ndb/latest/model.html#google.cloud.ndb.model.Model, entity3 = MyModel(key=ndb.Key(MyModel, "e-three")). It looks like you want

class Word(ndb.Model):
  definition = ndb.StringProperty(required=True)

new_word = Word(key=ndb.Key(Word, 'love'), definition='a profoundly tender, passionate affection for another person.')
new_word.put()

Then a lookup would be love_record = ndb.Key('Word', 'love').get().

Upvotes: 1

salyela
salyela

Reputation: 1645

I managed to solve it with the following

with client.context():
  word = Word(
    id = “love”,
    name = "love"
    “a profoundly tender, passionate affection for another person. ”
  )
word.put()

After I changed the class to this:

class Word(ndb.Model):
    name = ndb.StringProperty(required=True)
    definition = ndb.StringProperty(required=True)

Also I'm using Python3

Upvotes: 0

Related Questions