Skip to content Skip to sidebar Skip to footer

In Google App Engine, How Do I Avoid Creating Duplicate Entities With The Same Attribute?

I am trying to add a transaction to keep from creating two entities with the same attribute. In my application, I am creating a new Player each time I see a new Google user logged

Solution 1:

Use the username (or other identifier) as the key name, and use get_or_insert to transactionally create a new entity or return the existing one. Sahid's code won't work, because without a transaction, a race condition is still possible.

Solution 2:

Maybe you can use key name and get_by_key_name is better than filter.

defcreate_new_player(self,user_id):
    key_name = "player/%s" % user_id
    player = Player.get_by_key_name (key_name)
    if player isNone:
      player = Player (key_name=key_name, user_id=user_id)
      player.put ()
    return player

With the last comment of Nick, i have updated my code, so the better solution is:

defcreate_new_player(self,user_id):
      key_name = "player/%s" % user_id
      player = Player.get_or_insert (key_name=key_name, user_id=user_id)
      return player

Post a Comment for "In Google App Engine, How Do I Avoid Creating Duplicate Entities With The Same Attribute?"