views:

105

answers:

2

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

+4  A: 

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.

Alex Koshelev
+2  A: 

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')
Drew Sears