代码之家  ›  专栏  ›  技术社区  ›  Uri

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

  •  0
  • Uri  · 技术社区  · 9 年前

    我们正在使用Python中的谷歌应用引擎。我有代码将新对象保存到数据库,然后查询数据库以接收所有对象。问题是查询返回除我创建的新对象之外的所有对象。只有在刷新页面后,我才看到新对象。是否有方法更新查询以包含所有对象,包括我创建的新对象?这是我的代码:

    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 回复  |  直到 7 年前
        1
  •  1
  •   Mihail Russu    9 年前

    如评论中所述,这是一种预期行为。 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() 当没有结果时返回(None或[]?),您可能需要检查 features 是附加前的列表。您也可以避免第二个查询,因为您已经有了一个特性列表,可以在Python中循环使用它,而不是向数据存储发送另一个请求。