我正在使用ndbapi构建一个googleappengine应用程序(python2.7)。我是python开发新手,有一种感觉,这是一个以前已经回答过的问题,但是通过我的搜索,我无法找到类似于这个问题/解决方案的东西。我决定在这里提出我的问题。在
我有一个文档模型类,我需要查询并获取最“当前”的文档。具体地说,我想获得一个文档对象(实体)的列表,这些对象具有不同的文档名称,并且其expiration
日期(一个datetime.date
对象)是最大的值。在
例如,按到期日期降序查询文档,例如:
documents = Document.query().order(-Document.expiration).fetch()
退货:
^{pr2}$基于这些查询结果,我想删除第二个(较旧)出现的“DocumentA”并得到如下结果:
[{"name": "DocumentC", "expiration": datetime.date(2015, 3, 1)},
{"name": "DocumentA", "expiration": datetime.date(2014, 4, 1)},
{"name": "DocumentB", "expiration": datetime.date(2014, 2, 15)}]
我的解决方案是:
def current_docs(docs):
output = []
for d in docs:
if not any(o['name'] == d['name'] for o in output):
output.append(d)
return output
cd = current_docs(documents)
# returns:
# [{'expiration': datetime.date(2015, 3, 1), 'name': 'DocumentC'},
# {'expiration': datetime.date(2014, 4, 1), 'name': 'DocumentA'},
# {'expiration': datetime.date(2014, 2, 15), 'name': 'DocumentB'}]
这似乎给了我预期的结果,但是:
我对你第二个问题的回答是:
保存一个已经添加的名字的字典,只添加那些还没有添加的名字。但对谷歌应用引擎一无所知:)
如果您的数据满足文档中提到的限制,那么您应该能够使用投影查询和}来完成这项工作。在
group_by=["name"]
和{或者,我建议将数据保存到一个预计算的表中,该表只包含唯一的文档名和它的最新数据/状态。在写入时会产生额外的开销,但是读取速度很快,而且不必依赖于未过滤的数据集,如果您打算在运行时进行过滤,那么这是必需的。在
相关问题 更多 >
编程相关推荐