andrefaria
andrefaria

Reputation: 117

Google App Engine Incremental Identifier (ID)

I'm building a software for a school hosted at GAE and I need to create and sequence identifier to a new student when created, it doesn't really need to be the "key", but need this number to be incremented by one, each time a new student is added, it's gonna be the student number printed at the school card.

Using the low level API, I'm doing this:

student = new Entity("student")
student << params.subMap(["name", "birthdate"])
student.save()

It's creating the ID but it not been increment by one, it is kind of random...

I also tried to understand the KeyRange, but got nothing out of it.

Some help?

Upvotes: 1

Views: 2192

Answers (2)

max
max

Reputation: 30013

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

Upvotes: 0

sje397
sje397

Reputation: 41862

You can create an Entity using the Entity(String kind, String keyName) constructor:

new Entity("student", "" + id);

as long as the id is unique across all students.

To maintain an increasing counter, just use a normal datastore entity to store the count. The concurrency protections of the datastore (transactions) will neatly ensure sequential entity numbering. Sharded counters wont necessarily give you sequential ids (thanks @Nick Johnson).

One way to fetch by key name is (from here):

DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
Key key = KeyFactory.createKey("student", "" + id)
Entity entity = ds.get(key);

Upvotes: 1

Related Questions