Google App Engine(Python)- Datastore重复实体
我正在使用Google App Engine的Python开发工具包,还有一个叫做bottle的框架。
我运行了一些简单的代码,目的是设置一些实体来进行操作:
@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个实体,每个实体都有两个重复的副本。
1 个回答
3
在旧的数据库(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(Google App Engine)通常也会创建和销毁应用程序实例本身。所以每次创建新的应用程序实例时,也会创建一对新的 Statistic
实例。如果这些实例还不在数据库中,当你调用 put
函数时,它们会被添加到数据库里(这就是为什么你需要为每个实例指定一个 ID 的原因)。