This looks simple, but I just didn't find how to get an entity's id from Google App Engine's ndb.
class Message(ndb.Model):
name: ndb.StringProperty()
...
Create a message object:
message = Message(id=someId)
message.name = someName
message.put()
Later when I retrieve the entity:
message = Message.query(Message.name==someName).fetch(1)
Now how do I get the message's id? Thanks.
You can get the id with several ways provided you have the key.
Example with fetch
or get
:
message = Message.query(Message.name==someName).fetch(1)[0]
message_id = message.key.id()
message = Message.query(Message.name==someName).get()
message_id = message.key.id()
If you don't need the entity but only the id then you can save resources by getting only the key.
message_key = Message.query(Message.name==someName).fetch(1, keys_only=True)[0]
message_id = message_key.id()
message_key = Message.query(Message.name==someName).get(keys_only=True)
message_id = message_key.id()
Keep in mind that you can get the key after a put as well:
message_key = message.put()
message_id = message_key.id()
From Key Class NDB