get_or_insert: Was it get or insert?

30 views
Skip to first unread message

vivpuri

unread,
Sep 20, 2009, 10:30:19 AM9/20/09
to Google App Engine
When get_or_insert is used, is there a way to tell if it is a "get" or
the entity was really inserted?


Thanks

Robin B

unread,
Sep 20, 2009, 1:00:03 PM9/20/09
to 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

Sylvain

unread,
Sep 20, 2009, 2:08:31 PM9/20/09
to Google App Engine

ryan

unread,
Sep 21, 2009, 4:46:17 PM9/21/09
to Google App Engine
Reply all
Reply to author
Forward
0 new messages