google app engine's ndb: get an entity's id
Asked Answered
E

2

15

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.

Endotoxin answered 22/1, 2013 at 12:22 Comment(0)
F
38

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

Fusspot answered 22/1, 2013 at 12:58 Comment(2)
or after a put : message_id = message.put().id()Emerald
@Emerald yes but only on put because put() returns the Key instanceFusspot
P
1

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()
Pomiferous answered 7/2, 2014 at 0:1 Comment(1)
Thanks. You can as well do: message = Message.query(Message.name==someName).fetch(1)[0]Fusspot

© 2022 - 2024 — McMap. All rights reserved.