How do I define a unique property for a Model in Google App Engine?

Alex Bolotov picture Alex Bolotov · Jul 26, 2009 · Viewed 9.7k times · Source

I need some properties to be unique. How can I achieve this?

Is there something like unique=True?

I'm using Google App Engine for Python.

Answer

bizhobby picture bizhobby · Apr 29, 2011

Google has provided function to do that:

http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_or_insert

Model.get_or_insert(key_name, **kwds)

Attempts to get the entity of the model's kind with the given key name. If it exists, get_or_insert() simply returns it. If it doesn't exist, a new entity with the given kind, name, and parameters in kwds is created, stored, and returned.

The get and subsequent (possible) put are wrapped in a transaction to ensure atomicity. Ths means that get_or_insert() will never overwrite an existing entity, and will insert a new entity if and only if no entity with the given kind and name exists.

In other words, get_or_insert() is equivalent to this Python code:

def txn():
  entity = MyModel.get_by_key_name(key_name, parent=kwds.get('parent'))
  if entity is None:
    entity = MyModel(key_name=key_name, **kwds)
    entity.put()
  return entity
return db.run_in_transaction(txn)

Arguments:

key_name The name for the key of the entity **kwds Keyword arguments to pass to the model class's constructor if an instance with the specified key name doesn't exist. The parent argument is required if the desired entity has a parent.

Note: get_or_insert() does not accept an RPC object.

The method returns an instance of the model class that represents the requested entity, whether it existed or was created by the method. As with all datastore operations, this method can raise a TransactionFailedError if the transaction could not be completed.