【问题标题】:GqlQuery by ID always returns None resultGqlQuery by ID 总是返回 None 结果
【发布时间】:2013-10-05 13:46:40
【问题描述】:

我的代码旨在:

  • 从 cookie 中检索 user_id(如果存在)。
  • 使用 user_id 查询数据存储以检索用户记录。
  • 最后,如果找到一条记录,它会显示一条欢迎消息。 (注册被传递到模板)

我无法让应用显示欢迎消息。据我所知,问题是查询总是返回无。我已经验证了 cookie,并且数据存储中的数据存在。

这个查询我做错了什么? GQL 是否以不直观的方式处理 where 子句中的 ID?

#Get  cookie        
user_id = self.request.cookies.get("user_id", 0)

#Query Datastore for matching user_id
user = db.GqlQuery("SELECT * FROM User WHERE id = %s" % user_id).get()  

#If a user is found, display the username
if user.username:
    signup = "Welcome, %s" % user.username

【问题讨论】:

    标签: google-app-engine google-cloud-datastore gql gqlquery


    【解决方案1】:

    数据存储具有Key 属性,该属性由(可选)祖先、种类和名称或ID 组成。但是,没有特定的 id 属性。 (Reference)

    要获取具有特定键的实体,您的代码应如下所示:

    # Get cookie        
    user_id = self.request.cookies.get("user_id", 0)
    
    if not user_id:
      # handle this case, otherwise the call to from_path will fail.
    
    # Build key
    user_key = db.Key.from_path('User', long(user_id))
    
    # Get the entity
    user = db.get(user_key)
    
    # If a user is found, display the username
    if user.username:
        signup = "Welcome, %s" % user.username
    

    在这种情况下,您实际上不想使用查询,因为您已经知道要查找的实体的键。

    当你使用keys查询时,你必须指定整个key(不仅仅是id):

    user = db.GqlQuery("SELECT * FROM User WHERE __key__ > KEY('User', %s)" % user_id).get()
    

    请注意,这里我使用了不等式,因为您可以直接查找,因此对键使用等式过滤器没有意义。 Here 是在 GQL 字符串中使用 KEY 的参考,我在下面引用了相关部分:

    比较的右侧可以是以下之一(根据属性的数据类型):

    • 实体键字面量,具有字符串编码键或种类和键名称/ID 的完整路径:

      • KEY('encoded key')

      • KEY('kind', 'name'/ID [, 'kind', 'name'/ID...])

    【讨论】:

    • 好的,所以我之前使用 get_by_id 方法 user = User.get_by_id(int(user_id)) 得到了一些工作,但是当 cookie 不存在时遇到了错误。您的代码也会产生同样的错误。这是由于我在 user_id cookie 不存在时使用的默认值 user_id = self.request.cookies.get("user_id", 0)。原来 from_path() 方法不接受 0 作为 id_or_name 参数。来自 Google App Engine 文档:ID,指定为字符串或长整数。它不能是数字 0。
    • 啊,是的,你完全正确——丢失的 cookie 会破坏它。我会继续编辑代码,以免其他人遇到同样的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多