Google App Engine: Trouble with Datastore Query
This query works:
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0]
although if there are no results returned, it blows up in my face. (How can I get around this? A for
loop seems dubious when I want at max one iteration.)
This query does not work:
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN)[0]
CSIN
is a string representing a number. I get this error:
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 = 开发者_StackOverflowdb.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
What am I doing wrong here?
You're trying to get an item from a list (or a list-like object) that is empty. What you're doing is sort of comparable to the following:
>>> results = [] # an empty list
>>> item = results[0] # Raises an IndexError, because there is nothing in the list
What you need to do instead is:
item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = :1", CSIN).get()
Then, item
will be either None
or the first result from the query.
It seems that that your query returns an array or list of some sort, which is empty. Trying to access its non-existing first item raises an exception.
Try to figure out the length of the returned result before accessing it.
精彩评论