6

Has anyone got any example code for creating a unique number sequence to be used as keys for an entity in a Google app engine datastore?

Would like to use sequential order numbers as the key.

David Underhill
  • 15,896
  • 7
  • 53
  • 61
Ron Chan
  • 3,315
  • 5
  • 27
  • 31

2 Answers2

6

Use db.allocate_ids() as described here to generate unique IDs for your entities.

Here's a quick example derived from the example at the above link:

from google.appengine.ext import db

# get unique ID number - I just get 1 here, but you could get many ...
new_ids = db.allocate_ids(handmade_key, 1)

# db.allocate_ids() may return longs but db.Key.from_path requires an int (issue 2970)
new_id_num = int(new_id[0])

# assign the new ID to an entity
new_key = db.Key.from_path('MyModel', new_id_num)
new_instance = MyModel(key=new_key)
...
new_instance.put()

(issue 2970 reference)

David Underhill
  • 15,896
  • 7
  • 53
  • 61
  • 1
    Or just don't specify a key, and let the datastore generate one for you, which will have exactly the same effect. – Nick Johnson May 13 '10 at 18:22
  • @NickJohnson, that's [no longer true](https://cloudplatform.googleblog.com/2013/05/update-on-datastore-auto-ids.html) as of the 1.8.1 release of Google App Engine. – David Pärsson Jun 05 '16 at 11:15
2

You might want to look at How to implement "autoincrement" on Google AppEngine where you find a implementation of sequence numbers.

Community
  • 1
  • 1
max
  • 29,122
  • 12
  • 52
  • 79