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

How do I update a query from Google App Engine NDB?

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

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

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

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() returns 当没有结果时(None 或 [ ]?)您可能需要在追加之前检查 features 是否是一个列表.您也可以避免第二个查询,因为您已经有了一个功能列表,并且可以在 Python 中循环遍历它,而不是向数据存储区发送另一个请求。