【问题标题】:Custom key for app-engine datastore entity应用引擎数据存储实体的自定义键
【发布时间】:2021-05-22 16:50:25
【问题描述】:

我想在数据存储上创建一个简单的字典。所以我尝试像这样创建我的实体类

class Word(ndb.Model):
    id = ndb.KeyProperty(required=True)
    definition = ndb.StringProperty(required=True)

id 是实际单词。问题是当我尝试添加实体时,我收到一个错误,例如“爱”不是钥匙。于是我改成了下面的

class Word(ndb.Model):
    id = ndb.StringProperty(required=True)
    definition = ndb.StringProperty(required=True)

这种新方法的问题是我的 id 字段不被视为实体的实际 ID。数据存储创建了我的 id 字段以及另一个 Name/ID 字段。如何在 App-Engine 上使用自定义 ID?

这是我添加单词的方式:

word = Word()
word.id = “love”
word.definition =“a profoundly tender, passionate affection for another person. ”
word.put()

我希望不必使用this NamedModel recommendation,而是使用类似于this short one 的东西,除了我的结构化模型类。

【问题讨论】:

    标签: python google-app-engine google-cloud-datastore


    【解决方案1】:

    与其他数据库系统不同,Datastore 的键不是用户定义的列。主键始终作为显式项存在。

    来自https://googleapis.dev/python/python-ndb/latest/model.html#google.cloud.ndb.model.Modelentity3 = MyModel(key=ndb.Key(MyModel, "e-three"))。看起来像你想要的

    class Word(ndb.Model):
      definition = ndb.StringProperty(required=True)
    
    new_word = Word(key=ndb.Key(Word, 'love'), definition='a profoundly tender, passionate affection for another person.')
    new_word.put()
    

    然后查找将是love_record = ndb.Key('Word', 'love').get()

    【讨论】:

      【解决方案2】:

      我设法用以下方法解决了它

      with client.context():
        word = Word(
          id = “love”,
          name = "love"
          “a profoundly tender, passionate affection for another person. ”
        )
      word.put()
      

      在我把课程改成这样之后:

      class Word(ndb.Model):
          name = ndb.StringProperty(required=True)
          definition = ndb.StringProperty(required=True)
      

      我也在使用 Python3

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-19
        • 1970-01-01
        • 1970-01-01
        • 2011-05-13
        • 2013-09-30
        • 1970-01-01
        相关资源
        最近更新 更多