Our team is relatively new to AppEngine and we’re still learning the ropes. We’re using plain ndb.Model models (i.e. nothing fancy) and webapp2 handlers. The app is UI-less since it’s just a restful API.
So we have a model defined as such:
from google.appengine.ext import ndb
class Pasta(ndb.Model):
type = ndb.StringProperty(indexed=True)
name = ndb.StringProperty()
contents = ndb.JsonProperty()
modified_date = ndb.DateTimeProperty(auto_now=True)
added_date = ndb.DateTimeProperty(auto_now_add=True)
And the use case is that we would like to add a record if one doesn’t exist and if it does exist, return it. We could query for it in the handler and even create one there and use the pasta.put() instance method to create a new one. However, we think that data-bound code belongs in the model, not the handler, but, if we’re not mistaken, in the model context we need to use the get_or_insert() which requires we explicitly declare a Key, correct?
Any suggestions how to handle this sort of logic in the model? TIA.
I don’t know why you think the decision on whether the code goes in the model or the handler determines the method you use to do the query. You can use
get_or_insertin either place, but it does mean that you need to know the key of the entity you want. And, you can do queries in either place.If you do want to keep all your data interaction within the model, one possible pattern is to define a classmethod on the model that does the query and returns either the existing instance or a new one. Something like:
(Note I haven’t actually used ndb, but this is more or less right.) You’ll want to make sure this method is called within a transaction.