zspotter
zspotter

Reputation: 13

How do you fetch the N newest Models in Google App Engine with NDB?

I have potentially thousands of 'Report' Models stored. I'm trying to get the 50 newest Reports ordered by a DateTimeProperty. Although my existing query does fetch the Reports in order of new to old, it does not return the newest 50. Instead it returns an older (sorted) selection. What am I missing here?

class Report(ndb.polymodel.PolyModel):
    received_time = ndb.DateTimeProperty(required=True, auto_now_add=True)
    report_state = ndb.StringProperty(choices=set(['unresolved', 'resolved']))

...

reports_query = Report.query(
    Report.report_state == 'resolved',
    ancestor = some_key) \
    .order(Report.received_time)
resolved_reports = reports_query.fetch(50)

When I'm testing, if I have 200 Reports in my datastore and I fetch 200, I am getting all Reports sorted in the right order.

Upvotes: 1

Views: 133

Answers (1)

Peter Knego
Peter Knego

Reputation: 80340

Your query sorts in the increasing order of the received_time, so you are getting those with earlier times (smaller time = older time). To get the oldest ones change the order:

.order(-Report.received_time)

Upvotes: 3

Related Questions