Getting Datastore Key before inserting data

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Getting Datastore Key before inserting data



Cloud Datastore (Entities, Properties, and Keys) allows entities to be identified with an automatically generated numeric ID (or enter a custom name).



I'd like to use the automatically generated numeric ID in some business logic before the entity is written to the Datastore.


from google.cloud import datastore

ds = datastore.Client('my-project-id')

# Use automatically generated numeric ID.
key = ds.key('MyEntity')

# https://googlecloudplatform.github.io/google-cloud-python/latest/datastore/keys.html
my_id = key.id()

# Some business logic requiring unique ID for MyEntity
data = my_business_logic(my_id)

entity = datastore.Entity(key=key)
entity.update(data)
ds.put(entity)



However, key.id() is None and so I get a Python TypeError:


key.id()


None


TypeError: 'NoneType' object is not callable



Key is documented, so perhaps I'm using the wrong getter?




1 Answer
1



By default, entities won't have a complete key (with the numeric ID) until they're put() into the datastore.


put()



For a case like yours where you want to know the auto-generated numeric ID before writing the entity to the datastore, you can use the datastore client's allocate_ids method, like so:


allocate_ids


from google.cloud import datastore

ds = datastore.Client('my-project-id')

key = ds.allocate_ids(ds.key('MyEntity'), 1)[0]

my_id = key.id

data = my_business_logic(my_id)

entity = datastore.Entity(key=key)
entity.update(data)
ds.put(entity)



Note that allocate_ids takes 2 arguments, incomplete_key and num_ids, so even if you just want one key, you'll need to specify that and extract the first (and only) member of the resulting list.


allocate_ids


incomplete_key


num_ids






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS