python - 谷歌应用引擎 : Trouble with Datastore Query

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

此查询有效:

item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0]

虽然如果没有返回任何结果,它会在我面前爆炸。 (我怎样才能解决这个问题?当我想要最多一次迭代时,for 循环似乎很可疑。)

这个查询不起作用:

item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0]

CSIN 是一个代表数字的字符串。我收到此错误:

Traceback (most recent call last):
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\webapp\__init__.py", line 507, in __call__
    handler.get(*groups)
  File "path\to\src\Main.py", line 42, in get
    item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0]
  File "C:\Program Files\Google\google_appengine\google\appengine\ext\db\__init__.py", line 1717, in __getitem__
    raise IndexError('The query returned fewer than %d results' % (arg+1))
IndexError: The query returned fewer than 1 results

我在这里做错了什么?

最佳答案

您正试图从一个空列表(或类似列表的对象)中获取一个项目。您正在做的事情类似于以下内容:

>>> results = [] # an empty list
>>> item = results[0] # Raises an IndexError, because there is nothing in the list

你需要做的是:

item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN).get()

然后,item 将是 None 或查询的第一个结果。

关于python - 谷歌应用引擎 : Trouble with Datastore Query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2364531/

相关文章:

python - Syncano v4 错误 : "You do not have permission to perform this action"

python - 使用 python 将字符串时间戳转换为纪元时间的最快方法是什么?

google-app-engine - 是否可以将 Google App 引擎 Flexi 与 Cloud Nat 连接起来

java - 新的 Google App Engine 数据存储 API 似乎没有抛出那么多异常?

使用 Google Cloud Datastore API 的 Spring Boot 无法运行

python - 我有一个字符串,其内容是函数名,Python中如何引用对应的函数?

Python:AND 评估的优化

python - 在 webapp2 中,如何获取所有路由 URI 的列表?

html - CSS 文件在本地主机上不起作用

python - 使用浏览器查看时,创建数据存储条目会导致加密属性