2

I'm using Google App Engine NDB. Sometimes I will want to get all users with a phone number in a specified list. Using queries is extremely expensive for this, so I thought I'll just make the id value of the User entity the phone number of the user so I can fetch directly by ids.

The problem is that the phone number field is optional, so initially a User entity is created without a phone number, and thus no value for id. So it would be created user = User() as opposed to user = User(id = phone_number).

So when a user at a later point decides to add a phone number to his account, is there anyway to modify that User entity's id value to the new phone number?

Snowman
  • 31,411
  • 46
  • 180
  • 303
  • Maybe I do not understand in correct? Get the old entity id, delete it an put the new entity id. – voscausa Oct 19 '12 at 15:19
  • @voscausa well it's the same entity. The id is the entity's key. In NDB its referred to as id rather than key_name – Snowman Oct 19 '12 at 15:27
  • NDB Docs: A Key name (i.e., a string key ID) to retrieve or create. So when it is a string, it is a key name. – voscausa Oct 19 '12 at 15:31
  • @voscausa right, so now is it possible to change this key_name after an entity has already been created? – Snowman Oct 19 '12 at 15:32
  • Yes I think so. Guido saw no reason for an extra method to get by key_name. Because you can identify if the "NDB id" holds an id or a name (datastore). – voscausa Oct 19 '12 at 15:37

1 Answers1

3

The entity ID forms part of the primary key for the entity, so there's no way to change it. Changing it is identical to creating a new entity with the new key and deleting the old one - which is one thing you can do, if you want.

A better solution would be to create a PhoneNumber kind that provides a reference to the associated User, allowing you to do lookups with get operations, but not requiring every user to have exactly one phone number.

Nick Johnson
  • 100,655
  • 16
  • 128
  • 198