-1

How do I set an entity's key in my code.

Example, I have a user class

class User(ndb.Model)
  email

I want to be able to set email property and query using email property

my_user = User(email='xyz@ab.com')

Above statement sets email property, but Google App Engine generates its own key.

Can I set the key using User(key='xyz@ab.com')

If I can set the key property in a entity, how do I query for an entity using the key

Does this work User.query(key='xyz@ab.com').get()

I realize that I can query using email as a property, but unfortunately I can't do that in context of a transaction.

That is the reason I am asking how to get(), set() by keys.

Also, when I end up querying by properties, I need to create indexes on properties, which I know will be unique

user462455
  • 12,838
  • 18
  • 65
  • 96

1 Answers1

2

Yes, but it's not my_user = User(key='xyz@ab.com'), it's:

my_user = User(id='xyz@ab.com')
my_user_key = my_user.put()

Now, my_user_key is the key, so you can get it by:

the_user_entity = my_user_key.get()

Or, later, you can get it by constructing a Key:

my_user_key = ndb.Key(User, id='xyz@ab.com')
the_user_entity = my_user_key.get()

or directly by:

User.get_by_id('xyz@ab.com')
GAEfan
  • 11,244
  • 2
  • 17
  • 33
  • Thanks! How do I query for user with email 'xyz@abc.om' User.query(id='xyz@ab.com').get() ,or User.get_by_id('xyz@ab.com')> Does App engine have indices on `id` property automatically, or should I include a index in index.yaml for 'id' property – user462455 Nov 17 '16 at 01:43
  • Yes, the key is indexed on every entity, else it would not be queryable. Either of the methods in my answer work (using `get()` from a Key, or `get_by_id()`. A query is unnecessarily expensive. – GAEfan Nov 17 '16 at 01:59
  • Thanks! How do I access `id` property on ndb.Model object. If I have a user object, doing user.id gives an error saying User(ndb.Model) has no attribute `id` – user462455 Nov 17 '16 at 03:50
  • `user.key.id()` – GAEfan Nov 17 '16 at 03:59
  • Beware that using the email address as ID adds issues if the user wants to change their email address later. – GAEfan Nov 17 '16 at 16:56