Franz Noel
Franz Noel

Reputation: 1880

Check If Entity in Datastore exists in GAE Python

I'm trying to create (something like) an invoice number generator. But, since Invoices may be zero or more when starting a business, how do you know if an entity exists?

query = "SELECT loanNumber FROM Loans ORDER BY loanNumber DESC LIMIT 1"
loanNumbers = db.GqlQuery(query)

result = loanNumbers.get()

# for loanNumber in loanNumbers:
if loanNumbers is None:
  print "Print the first number"
else:
  print "Print the next number"

Error

KindError: No implementation for kind 'Loans'

Upvotes: 3

Views: 1259

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169284

Now there are some nice metadata helper functions documented here: https://developers.google.com/appengine/docs/python/datastore/metadataentityclasses#get_kinds

Here is an example of checking for Loans before continuing with your query and the rest of your code:

from google.appengine.ext.db import metadata

my_kinds = metadata.get_kinds() # Returns a list of entity kind names.

if u'Loans' in my_kinds:
    ...

Note that my_kinds will not contain Loans until a loan entity has actually been created.


If you require more control, or prefer to roll your own helper function there are examples of that here: https://developers.google.com/appengine/docs/python/datastore/metadataqueries#Kind_Queries

Upvotes: 3

Related Questions