【问题标题】:Creating a App Engine Datastore entity创建 App Engine 数据存储区实体
【发布时间】:2013-01-14 16:38:38
【问题描述】:
我正在使用谷歌应用引擎,我正在尝试使用代码插入实体/表:
class Tu(db.Model):
title = db.StringProperty(required=True)
presentation = db.TextProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
last_modified = db.DateTimeProperty(auto_now=True)
。
.
.
a = Tu('teste', 'bla bla bla bla')
a.votes = 5
a.put()
但我收到此错误:
TypeError: Expected Model type; received teste (is str)
我正在关注此文档 https://developers.google.com/appengine/docs/python/datastore/entities,但我看不出我错在哪里。
【问题讨论】:
标签:
python
google-app-engine
google-cloud-datastore
【解决方案1】:
当您以这种方式创建模型时,您需要为模型的所有属性使用关键字参数。这是来自db.Model 的__init__ 签名的sn-p,您的Tu 模型继承自该签名:
def __init__(self,
parent=None,
key_name=None,
_app=None,
_from_entity=False,
**kwds):
"""Creates a new instance of this model.
To create a new entity, you instantiate a model and then call put(),
which saves the entity to the datastore:
person = Person()
person.name = 'Bret'
person.put()
You can initialize properties in the model in the constructor with keyword
arguments:
person = Person(name='Bret')
# continues
当您说a = Tu('teste', 'bla bla bla bla') 时,由于您没有提供关键字参数而是将它们作为位置参数传递,所以teste 被分配给__init__ 中的parent 参数(而bla bla bla bla 被分配给key_name) 并且由于该参数需要 Model 类型的对象(我假设您没有),因此您会收到该错误。假设您尝试将这些项目添加为title 和presentation,您会说(正如@DanielRoseman 已经简洁陈述的那样:)):
a = Tu(title='teste', presentation='bla bla bla bla')
【解决方案2】:
您链接到的文档都使用关键字参数:
a = Tu(title='tests', presentation='blablablah')
如果使用位置参数,第一个参数被解释为父级,它需要是 Model 或 Key 类型。