Google Groups

Re: get_or_insert: Was it get or insert?


Robin B Sep 20, 2009 10:00 AM
Posted in group: Google App Engine
You can view the source of get_or_insert and see that it only returns
the entity:

  @classmethod
  def get_or_insert(cls, key_name, **kwds):
    def txn():
      entity = cls.get_by_key_name(key_name, parent=kwds.get
('parent'))
      if entity is None:
        entity = cls(key_name=key_name, **kwds)
        entity.put()
      return entity
    return run_in_transaction(txn)

Try adding this modified classmethod to your model:

  @classmethod
  def get_or_insert2(cls, key_name, **kwds):
    def txn():
      entity = cls.get_by_key_name(key_name, parent=kwds.get
('parent'))
      if entity is None:
        entity = cls(key_name=key_name, **kwds)
        entity.put()
        return (True,entity)
      return (False,entity)
    return run_in_transaction(txn)

Use it like this:

inserted,entity = MyModel.get_or_insert2('foobar',**attrs)
if inserted:
    print "inserted"
else:
    print "existing"


Robin


On Sep 20, 9:30 am, vivpuri <v...@vivekpuri.com> wrote:
> When get_or_insert is used, is there a way to tell if it is a "get" or
> the entity was really inserted?
>
> Thanks