EsseTi EsseTi - 7 months ago 35
Python Question

Ndb default order does not preserve insertion order

I used GAE and NDB for a project. I just noticed that if I create several objects, and then I retrieve the list of these objects the order is not preserved (i use the

on the object).

This is a screenshot of the admin page, which shows the same problem:

as you may (if it's too small here is the link) see i've several
. Now, i created the sessions that have as name
in order, from 0 to 7.

But as you see the order is not preserved.

I checked and actually the
are not incremental. Neither the
should be incremental, shouldn't it? but anyway in some classes, not this one, I used a hand-made key, so there will be no

Is there a way to preserve insertion order?
(or it's just a strange behaviour? or it's my bad?)

PS: if you want to have a look at the code: this is the session model which extends this class i made


Neither keys nor ids are strictly incremental (and incremental by one) in ndb. You can set your own ids and assure they autoincrement properly.

Or you can add to your model(s) a DateTimeProperty:

created = ndb.DateTimeProperty(auto_now_add=True)

And in your view you can use a filter to sort the entities by the date of insertion, for ex:

posts = Post.query().order(-Post.created).fetch()

which will order and fetch your (let's say) Post entities in the descending order of insertion dates.