10

For the following (broken) function, I want to return True if the entity was created or updated, and False otherwise. The problem is that I do not know whether get_or_insert() got an existing entity, or inserted one. Is there an easy way to determine this?

class MyModel(ndb.Model):
    def create_or_update(key, data):
        """Returns True if entity was created or updated, False otherwise."""

        current = MyModel.get_or_insert(key, data=data)

        if(current.data != data)
            current.data = data
            return True

        return False
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
Matt Faus
  • 6,321
  • 2
  • 27
  • 43

1 Answers1

30

get_or_insert() is a trivial function (although its implementation looks complex, because it tries to deal with unusual property names). You can easily write it yourself:

@ndb.transactional
def my_get_or_insert(cls, id, **kwds):
  key = ndb.Key(cls, id)
  ent = key.get()
  if ent is not None:
    return (ent, False)  # False meaning "not created"
  ent = cls(**kwds)
  ent.key = key
  ent.put()
  return (ent, True)  # True meaning "created"
Guido van Rossum
  • 16,690
  • 3
  • 46
  • 49
  • Sorry for my ignorance, but shouldn't there be a `@classmethod` above `@ndb.transactional`? Thanks – Houman Jul 20 '14 at 22:49
  • 1
    @Hooman, if you're using it inside a class, then yes, but in its current function form, you can use it with any `Model` class, by passing the class as the first argument. – Mansour Sep 05 '14 at 12:03