简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM