如何从Google App Engine NDB更新查询?

时间:2015-01-29 11:10:11

标签: python google-app-engine google-cloud-datastore app-engine-ndb

我们在Python中使用Google App Engine。我有代码将新对象保存到数据库,然后查询数据库以接收所有对象。问题是查询返回除了我创建的新对象之外的所有对象。只有在刷新页面后,我才会看到新对象。有没有办法更新查询以包括所有对象,包括我创建的新对象?这是我的代码:

if (self.request.get("add_a_new_feature") == "true"):
    features = Feature.gql("WHERE feature_name=:1 ORDER BY last_modified DESC LIMIT 1", NEW_FEATURE_NAME) # class Feature inherits from ndb.Model
    if (features.count() == 0):
        new_feature = Feature(feature_name=NEW_FEATURE_NAME)
        new_feature.put()
...
features = Feature.gql("ORDER BY date_created")
if (features.count() > 0):
    features_list = features.fetch()
    for feature in features_list:
        ... # the list doesn't contain new_feature

1 个答案:

答案 0 :(得分:1)

如评论中所述 - 这是预期的行为。 Take a look at this article for additional information.作为快速修复/破解,您可以在添加新实体之前简单地从数据存储区获取数据,然后将其附加到列表中。

features = Feature.gql("ORDER BY date_created")

if (self.request.get("add_a_new_feature") == "true"):
    if (Feature.gql("WHERE feature_name=:1 ORDER BY last_modified DESC LIMIT 1", NEW_FEATURE_NAME).count() == 0):
        new_feature = Feature(feature_name=NEW_FEATURE_NAME)
        new_feature.put()
        features.append(new_feature)
...

if (features.count() > 0):
    features_list = features.fetch()
    for feature in features_list:
        ... # the list now contain the new_feature at the end

根据Entity.gql()在没有结果(无或[??)时返回的内容,您可能需要在追加之前检查features是否为列表。您也可以避免第二个查询,因为您已经有一个功能列表,可以在Python中循环它,而不是向数据存储区发送另一个请求。