views:

61

answers:

2

Hello,

I want to be able to check if a key_name for my model exists in the datastore. My code goes:

t=MyModel.get_by_key_name(c)
    if t==None:
        #key_name does not exist

I don't need the object, so is there a way (which would be faster and cost less resource) to ccheck if the object exist without returning it? I only know the key name, not the key.

+1  A: 

You can't avoid get_by_key_name() or key-related equivalents to check if a key exists. Your code is fine.

moraes
A: 

The API talks about Model.all(keys_only=False) returning all the key names when keys_only is set to True

Look at the query that is fired for this, and then you can write a query similar to this but just for your object and see if any row is fetched or not.

Rahul
A query is not a better option, even with keys_only. They are much slower than getting by keys. The only performance improvement would be to use low level datastore apis, but I'd not recommend this because it is more complex and harder to maintain.
moraes
Please correct me if I am wrong since All these thoughts from the 30 odd minutes I spent reading http://code.google.com/appengine/docs/python/datastore/modelclass.html with no prior knowledge or deeper research : A query retrieving the key_name is faster than retrieving the object to see if the key exists. Also, get_by_key_name() eventually fires a query to retrieve the object if it exists. The key_exists() methods should have been a part of the API. I just suggested a way for him/her to do so.
Rahul
datastore.Get and datastore.Query are different things. get_by_key_name() doesn't perform a query -- it builds a key and uses datastore.Get in the end, which is a few times faster than a datastore.Query, even if it is a keys_only query. See the latency of both get and query: http://code.google.com/status/appengine/detail/datastore/2010/08/31#ae-trust-detail-datastore-get-latency
moraes