【问题标题】:Google App Engine: defining custom id and queryingGoogle App Engine:定义自定义 ID 和查询
【发布时间】:2014-01-17 01:00:10
【问题描述】:

我想将自定义字符串定义为 ID,因此我创建了以下模型:

class WikiPage(ndb.Model):
    id = ndb.StringProperty(required=True, indexed=True)
    content = ndb.TextProperty(required=True)
    history = ndb.DateTimeProperty(repeated=True)

基于这个SO thread,我相信这是对的。

现在我尝试通过这个 id 查询:

entity = WikiPage.get_by_id(page) # page is an existing string id, passed in as an arg

这是基于NDB API

然而,这并没有返回任何东西——实体是无。 它仅在我运行以下查询时才有效:

entity = WikiPage.query(WikiPage.id == page).get()

我是否错误地定义了我的自定义密钥或以某种方式滥用 get_by_id()?

【问题讨论】:

  • 嗯,查看数据存储区,好像我没有正确定义 id/key。未强制执行唯一约束。
  • 您已将 id 字段用作字符串属性。重命名它,并将这个新字段用作模型的 id。
  • @voscausa 抱歉,您能详细说明一下吗?
  • id 是特殊的,是 ndb.Key 的一部分,请参见下面的示例。

标签: python google-app-engine


【解决方案1】:

例子:

class WikiPage(ndb.Model):
    your_id = ndb.StringProperty(required=True)
    content = ndb.TextProperty(required=True)
    history = ndb.DateTimeProperty(repeated=True)

entity = WikiPage(id='hello', your_id='hello', content=...., history=.....)
entity.put()

entity = WikiPage.get_by_id('hello')

key = ndb.Key('WikiPage','hello')
entity = key.get()
entity = WikiPage.get_by_id(key.id())

这仍然有效:

entity = WikiPage.query(WikiPage.your_id == 'hello').get()

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多