我正在为 Google App Engine 和 bottle 使用 Python SDK。
像这样运行一些简单的东西来设置一些要使用的实体:
@bottle.route('/test')
def testing():
Statistic(team_id = 2, qty_customers = 600).put()
Statistic(team_id = 3, qty_customers = 5).put()
return "Done."
统计看起来像这样:
class Statistic(ndb.Model):
team_id = ndb.IntegerProperty()
qty_customers = ndb.IntegerProperty()
我希望它为每个实体创建一个实体,并将它们添加到数据存储区。它为每个创建两个副本并将它们添加到数据存储区。
如何让代码只添加一个实体?
为什么要创建两个?
编辑: 澄清一下,我运行了一次 testing() 函数,它创建了 4 个实体。每个一式两份。
请您参考如下方法:
在旧数据库 (db.Model) 中,您必须在创建实例时指定 key_name。
在新的数据库(ndb.Model)中,您需要指定id,否则会选择递增的整数。
因此调用函数 testing 两次会产生四个不同的 Statistic 实例,ID 分别为 1、2、3 和 4。
如果您为每个 Statistic 实例明确指定不同的 ID,那么您将只会获得两个实例。
我相信在您的情况下,您不妨删除 team_id 字段:
class Statistic(ndb.Model):
qty_customers = ndb.IntegerProperty()
然后,为您创建的每个 Statistic 实例指定一个唯一 ID:
def testing():
Statistic(id = 2, qty_customers = 600).put()
Statistic(id = 3, qty_customers = 5).put()
顺便说一句,我认为建议使用字符串 ID 而不是整数 ID:
def testing():
Statistic(id = '2', qty_customers = 600).put()
Statistic(id = '3', qty_customers = 5).put()
更新:
即使您只在应用程序中调用函数 testing 一次,GAE 也经常创建和销毁应用程序实例本身。因此,每次创建应用程序的新实例时,也会创建一对新的 Statistic 实例。如果这些实例不在数据库中,那么它们会在您调用函数 put 时添加到数据库中(这就是为什么您需要为每个实例指定一个 ID)。
