In MySQL you can get the next or previous record based on the key/id. Anyone know how i can achieve this in app engine (im using python) by only knowing/passing the key? Thanks
Asked
Active
Viewed 422 times
3 Answers
2
There's no way (by default) for an entity to know the next/previous entity.
One thing you could do is give each model a timestamp for the time they were created, then getting the next entity is as easy as selecting the first entity whose timestamp is after XXX.

Jason Hall
- 20,632
- 4
- 50
- 57
-
how to compare timestamp? I have DateTimeProperty for each entity. Thanks – John Jul 31 '13 at 04:46
2
Assuming that by 'next/previous', you mean 'the entity with the key that is lexicographically closest to a given key', yes, you can do this using queries. Supposing your key is in 'my_key', and your model is called MyModel, in Python it would work like this:
q = MyModel.all().filter('__key__ >', my_key)
next_entity = q.get()
q = MyModel.all().filter('__key__ <', my_key)
prev_entity = q.get()

Nick Johnson
- 100,655
- 16
- 128
- 198
-
given a model with user defined key_names it seems that 'previous' always rolls one back to the 'first' entry. In other words given 5 records with key_names 1,2,3,4,5 the record previous to 3 is 1, previous to 4 is 1. How does one get the 'immediately previous' or the 'last' record in the resulting query??? – molicule Mar 11 '11 at 18:49
-
@molicule That certainly shouldn't be the case. Can you provide a complete example that reproduces this? – Nick Johnson Mar 11 '11 at 18:50
-
What happens with AppEngine DataStore "Eventual Consitenciy"? If your App has heavy load, then getting the next id will not ensure you that will be the "greatest" when you want to store it. You've to be careful with it, and consider using transactions. By the way, Great answer Nick! +1 – santiagobasulto Jun 21 '11 at 21:44
-
@santiagobasulto The OP didn't specify they wanted this for key generation, and indeed it shouldn't be used as such on either the MS or HR datastores - it's not transaction safe and can't be made so. – Nick Johnson Jun 21 '11 at 23:51
-
@Nick. Can't it made with transactions? I would bet it could. Thanks for your comment, i'll take a look. – santiagobasulto Jun 22 '11 at 11:30
-
@santiagobasulto No, because you can't do queries inside transactions unless you specify an ancestor filter. – Nick Johnson Jun 22 '11 at 11:53
1
This worked for me:
q = Noticia.all().filter("tipo",tipo).filter('____key____ <', bookmark).order("-____key____")
next = q.get()
q = Noticia.all().filter("tipo",tipo).filter('____key____ >', bookmark)
prev = q.get()

dandan78
- 13,328
- 13
- 64
- 78

Jose Leonel Boa
- 11
- 1