Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google app engine's ndb: get an entity's id

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.

like image 688
Randy Tang Avatar asked Jan 22 '13 12:01

Randy Tang


People also ask

How do I find my app engine code?

You can view and copy the source code in Console -> App Engine -> Versions -> press 'tools' under specific version and choose 'source'.

What is cloud NDB?

App Engine NDB enables Python 2 apps to store and query data in Firestore in Datastore mode (Datastore) databases. Cloud NDB enables Python 2 and Python 3 apps to store and query data in the same databases and uses Datastore as the product that manages those databases.

How do I delete a entity in Datastore?

const taskKey = datastore. key('Task'); await datastore. delete(taskKey);


2 Answers

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

like image 186
Jimmy Kane Avatar answered Oct 25 '22 23:10

Jimmy Kane


Try using get() to for a single instance

message = Message.query(Message.name==someName).get()
message.key.id()

fetch() returns a list object so your code will need to be roughly this:

messages = Message.query(Message.name==someName).fetch(1)
message = messages[0]
message.key.id()
like image 20
user1555671 Avatar answered Oct 25 '22 22:10

user1555671