Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google App Engine: get_or_create()?

Does Google App Engine have an equivalent of Django's get_or_create()?

like image 981
Nick Heiner Avatar asked Jun 05 '10 18:06

Nick Heiner


People also ask

Can App Engine scale to zero?

Scaling characteristics While both environments use App Engine's automatic scaling infrastructure, the way in which they scale is different. The standard environment can scale from zero instances up to thousands very quickly.

What is the use of Google App Engine?

App Engine is a fully managed, serverless platform for developing and hosting web applications at scale. You can choose from several popular languages, libraries, and frameworks to develop your apps, and then let App Engine take care of provisioning servers and scaling your app instances based on demand.


2 Answers

There is no full equivalent, but get_or_insert is something similar. The main differences is that get_or_insert accepts key_name as lookup against filters set in get_or_create.

like image 82
Alex Koshelev Avatar answered Sep 21 '22 11:09

Alex Koshelev


Haven't tested this, but it should be something like the following:

class BaseModel(db.Model):
  @classmethod
  def get_or_create(cls, parent=None, **kwargs):
    def txn():
      query = cls.all()
      if parent:
        query.ancestor(parent)
      for kw in kwargs:
        query.filter("%s =" % kw, kwargs[kw])
      entity = query.get()
      if entity:
        created = False
      else:
        entity = cls(parent, **kwargs)
        entity.put()
        created = True
      return (entity, created)
    return db.run_in_transaction(txn)

class Person(BaseModel):
  first_name = db.StringProperty()
  last_name = db.StringProperty()

p, created = Person.get_or_create(first_name='Tom', last_name='Smith')
like image 28
Drew Sears Avatar answered Sep 19 '22 11:09

Drew Sears