EsseTi EsseTi - 2 months ago 6
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

fetch()
on the object).

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

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

But as you see the order is not preserved.

I checked and actually the
keys
are not incremental. Neither the
id
(
id
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
id
).

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

Answer

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.