Google App引擎:没有key_name属性

时间:2014-06-20 17:28:37

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

我试图了解GAE是如何工作的,但是由于一些奇怪的原因,这段代码输出了

AttributeError: 'User_Account' object has no attribute 'key_name'

以下是相关的两个代码提取:

class User_Account(ndb.Model):
    name = ndb.StringProperty()
    firstname = ndb.StringProperty()


class AddUser(webapp2.RequestHandler):

    def get(self):
        test_user = User_Account(name = "snow", firstname ="jon", key_name="jon")

我已经尝试过使用db和ndb模型,它无论如何也无法工作......

提前感谢您的回答。

更新:在这里"完整"代码(我删除了所有其他不必要的部分):

import webapp2
import cgi
from google.appengine.ext import ndb


MAIN_PAGE_HTML = """\
<html>
  <body>
    <br/>
    <a href="/add_user"> Add a user </a>
  </body>
</html>
"""

class Comment(ndb.Model):
    content = ndb.StringProperty()

class User_Account(ndb.Model):
    name = ndb.StringProperty()
    firstname = ndb.StringProperty()
    comments = ndb.KeyProperty(repeated=True)


class AddUser(webapp2.RequestHandler):
    def get(self):
        test_user = User_Account(name = "jon", firstname ="snow", key_name="jon")
        self.response.write(test_user.key_name + "<br/>")

        test_user.put()

        self.response.write("User added")

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.write(MAIN_PAGE_HTML)


application = webapp2.WSGIApplication([
    ('/', MainPage),
    ('/add_user', AddUser)
], debug=True)

MOAR编辑: 即使是非常简单的代码,在开发控制台中执行时也会输出错误

import os
import pprint

from google.appengine.ext import ndb

class Comment(ndb.Model):
    content = ndb.StringProperty()


test_comment = Comment(content="Hello world", key_name="hello")
test_comment.put()

2 个答案:

答案 0 :(得分:4)

请阅读ndb模型类的文档。特别是关于模型构造函数的参数。 https://developers.google.com/appengine/docs/python/ndb/modelclass#Constructor

您会看到它需要id,而不是than key_namekey_namedb api的构造函数参数。

答案 1 :(得分:0)

我有一个类似情况的解决方案,我想要一个实体的key_name(只有key_name而没有ID)。我能够从属性self.key().name()

中找到key_name
相关问题