App Engine GQL Query - Sorting

北战南征 提交于 2019-12-11 06:22:22

问题


Having some issues with merging two GQLQueries in GAE (python).

  fp_events = db.GqlQuery("SELECT * FROM Event WHERE firstPlayer=:1", alias).fetch(mylimit)
  sp_events = db.GqlQuery("SELECT * FROM Event WHERE secondPlayer=:1", alias).fetch(mylimit)
  events = fp_events.append(sp_events)

However, when I try to iterate through these events using the for loop for event in events:, I get a TypeError: 'NoneType' object is not iterable error at that line. I suspect that this has something to do with the append I attempt to do, though I'm not entirely sure.

These events also have a datetime property... how could I sort the resulting events list by time, descending? While I could use ORDER BY time DESC in the two queries above, their merger isn't necessarily guaranteed to be sorted.

I should also mention that the firstPlayer and secondPlayer properties for the Event table are mutually exclusive (no event has both firstPlayer and secondPlayer set to the same player).

Thank-you!


回答1:


You can use list to convert the iterable objects into Python lists:

fp_events = db.GqlQuery("SELECT * FROM Event WHERE firstPlayer = :1", alias).fetch(mylimit)
sp_events = db.GqlQuery("SELECT * FROM Event WHERE secondPlayer = :1", alias).fetch(mylimit)

To combine the two lists, try this:

fp_events_list = list(fp_events)
sp_events_list = list(sp_events)
events = fp_events_list + sp_events_list

I just tried that out in the remote shell against one of my own AppEngine datastores, and it definitely works.

I'm afraid that in order to get the sorting that you want, you'll have to use sort them with the sorted builtin:

sorted_events = sorted(events, key=lambda event: event.time)


来源:https://stackoverflow.com/questions/11637677/app-engine-gql-query-sorting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!