St3114 St3114 - 21 days ago 6
Python Question

How to check if entity exist in gae datastore?

I need to check datastore if entity kind "Kayit" exist to create new .
my db.model class:

class Kayit(db.Model):
url=db.StringProperty()
date = db.DateTimeProperty(auto_now_add=True)


currently using this to check but it doesnt seem elegant

class MainPage(webapp2.RequestHandler):
def get(self):
r_name="none"
q=db.Query(Kayit)
try:
self.response.write(q[0].url)
except:
kay=Kayit(parent=_DefterKey(r_name),key_name='alibaba')
kay.url="some url"
kay.put()


I guess we get the parent key with db.Key.from_path('Kayit', 1) . how can I use to check if it has entities?

Answer

The was answered by:

How to query parent entity from child entity in Google App Engine (Python) NDB/Datastore?

documented in in the cloud API:

https://cloud.google.com/appengine/docs/java/javadoc/com/google/appengine/api/datastore/Entity

...and is shown in the python "Guestbook" google example:

https://cloud.google.com/appengine/docs/python/gettingstartedpython27/usingdatastore

Look at the stanza that goes:

 greetings_query = Greeting.query(
        ancestor=guestbook_key(guestbook_name)).order(-Greeting.date)
 greetings = greetings_query.fetch(10)