我正在使用适用于Google App Engine和瓶子的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(db.Model
)中,您必须key_name
在创建实例时指定。
在新的DB(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)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句