get_or_insert: Was it get or insert?

30 görüntüleme
İlk okunmamış mesaja atla

vivpuri

okunmadı,
20 Eyl 2009 10:30:1920.09.2009
alıcı 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

okunmadı,
20 Eyl 2009 13:00:0320.09.2009
alıcı 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

okunmadı,
20 Eyl 2009 14:08:3120.09.2009
alıcı Google App Engine

ryan

okunmadı,
21 Eyl 2009 16:46:1721.09.2009
alıcı Google App Engine
Tümünü yanıtla
Yazarı yanıtla
Yönlendir
0 yeni ileti