Why is this datastore querying by key returning None?
-
19-06-2021 - |
Question
1) When I perform this query:
contract_record = Contract(book_number = 42, initial_page = 420, final_page = 442)
contract_record.put()
contract_key = contract_record.key()
contract = db.GqlQuery("SELECT * FROM Contract WHERE __key__ = KEY('Contract', '$[contract_key]')").get()
The result is None. Why?
2) How to make this query not by the key, but the key_id? (something like this:
contract_id = contract_record.key().id()
contract = db.GqlQuery("SELECT * FROM Contract WHERE __key__ = KEY('Contract', '$[contract_id]')").get()
Thanks for any help!
Solution
What is '$[contract_key]'
supposed to be? Are you trying to do some sort of string substitution here? That really isn't how it works. Perhaps you mean to use the %s
operator?
In any case, I don't really understand why you insist on doing queries via GQL. The way to get an object by its key is directly with get
:
contract = db.get(contract_key)
and for the key ID:
contract = Contract.get_by_id(id)
OTHER TIPS
Maybe this is not the answer you are looking for, but you could try this:
contract_record = Contract(book_number = 42, initial_page = 420, final_page = 442)
contract_record.put()
contract_key = contract_record.key()
contract = db.get(contract_key)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow