NDB - 如何知道实体是否包含在根密钥

时间:2015-04-29 05:07:57

标签: google-app-engine

我想将玩家的数据添加到NDB中。但是在添加它们之前,我必须检查数据存储区中是否存在数据。我在官方文档中找不到明显的答案。谁能给我一个关于这个问题的简单代码和解释?这是我的代码的一部分。

self.player = Player(parent=ndb.Key("Players", "PlayersKeys"), name = self.request.get("Name"), playerid = self.request.get("ID"))
self.player.put()

更新-------------------

通过使用查询,如果它包含数据,那么qry.get()将不是None。

以下是我的解决方案:

qry = Player.query(Player.userid == self.request.get("ID"))
if qry.get() == None:
    # put the data to datastore
    self.player = Player(parent=ndb.Key("Players", "PlayersKeys"), name = self.request.get("Name"), userid = playerid)
    self.player.put()
else:
     # Do nothing

2 个答案:

答案 0 :(得分:0)

您必须知道实体的ID,即您的情况下的playerid,以及父级的密钥。

因此

myPlayer = Player.get_by_id(int(playerid),parent=parentKey)
if myPlayer:
    #The player already exists... do something
    pass
else:
    #The player does not exist (yet) you can create it
    pass

<强>更新

   playerCount= Player.query(Player.userid ==self.request.get("ID")).count(keys_only=True)
   if PlayerCount>0:
       #the player already exists
       pass
   else: 
       #the player does not exist
       pass

这不应该增加读取操作的数量

答案 1 :(得分:0)

答案是Player.get_or_insert

player_key = Player.query(Player.userid == self.request.get("ID")).get(keys_only=True)
player = Player.get_or_insert(player_key, **data)