Reputation: 20429
I have movies datastore, each record there has its own id as key name like below:
12345
32453
12154
78873
34543
I would like to allow user to browse movies one by one. Firstly, the latest movie should be shown (database has field added
with date and time). How to get that from the datastore?
Upd. I can do it like below:
movies = Movies.query()
movies.order(-Movies.added)
for movie in movies.fetch(1):
self.response.out.write(movie.key.id())
But I don't like it - in order to get key I request the whole record.
Secondly, if some other movie is shown (for ex., 12154), user should be able to go to previous movie (id 32453) and next movie (id 78873). Of course, if last movie is shown, there will not be next movie; and if first movie is shown, there will not be previous movie. So, the question is how to get key names of next and previous movies?
Upd. If current movie shown is 12154, then I should generate links like example.com/movie/32453
for previous movie and example.com/movie/78873
for the next one.
Upd. I've tried something like below:
next_movie = Movies.query(Movies.added < movie.added)
next_movie = next_movie.order(-Movies.added)
next_movie = next_movie.get()
if next_movie:
next_url = next_movie.key.id()
else:
next_url = ''
prev_movie = Movies.query(Movies.added > movie.added)
prev_movie = prev_movie.order(-Movies.added)
prev_movie = prev_movie.get()
if prev_movie:
prev_url = prev_movie.key.id()
else:
prev_url = ''
But it doesn't work well... next_url
seems to be OK, but prev_url
always the same. Here is my test database content (-Movies.added
order):
id added
503035: 2012-08-05 19:49:51.259000
475537: 2012-08-05 19:49:51.238000
677539: 2012-08-05 19:49:51.218000
566355: 2012-08-05 19:49:51.197000
557850: 2012-08-05 19:49:51.176000
670146: 2012-08-05 19:49:51.155000
581030: 2012-08-05 19:49:51.135000
464561: 2012-08-05 19:49:51.114000
507817: 2012-08-05 19:49:51.092000
Upvotes: 1
Views: 2135
Reputation: 20429
the following codes works well:
next_movie = Movies.query(Movies.added < movie.added)
next_movie = next_movie.order(-Movies.added)
next_movie = next_movie.get(keys_only = True)
if next_movie:
next_url = next_movie.id()
else:
next_url = ''
prev_movie = Movies.query(Movies.added > movie.added)
prev_movie = prev_movie.order(Movies.added)
prev_movie = prev_movie.get(keys_only = True)
if prev_movie:
prev_url = prev_movie.id()
else:
prev_url = ''
return next_url, prev_url
Upvotes: 1
Reputation: 80340
First you need a property on your movie entity that would represent "lateness", e.g. a date filed when movie was inserted in database.
Then you should use query with descending sort on this field.
To skip to next/previous you should use Query Cursors.
Upvotes: 2