Google App Engine,如何自动加载ReferenceProperty的模型类

时间:2010-06-30 09:05:16

标签: google-app-engine

我有模块化的项目结构,如下所示:

./main.py
./app.yaml
../articles
.../__init__.py
.../models.py
../blog
.../__init__.py
.../models.py
../comments
.../__init__.py
.../models.py

我已经在每个包的文件models.py中定义了模型(这是应用程序)。我为“评论”应用程序定义了下一个模型:

class Comment(db.Model):
    author      = db.UserProperty(auto_current_user_add=True)
    title       = db.StringProperty(default="Title")
    text        = db.TextProperty("Message", default="Your message")
    # references to any model
    object      = db.ReferenceProperty()

在“文章”应用程序中我定义了下一个模型:

class Article(db.Model):
    author      = db.UserProperty(auto_current_user_add=True)
    title       = db.StringProperty(default="Title")
    text        = db.TextProperty("Message", default="Your message")

1)首次加载页面时 - 我创建了新文章:

from articles.models import Article
article = Article(title="First article", text="This is first article")
article.put()

2)在第二次加载页面时,我创建了新评论:

from articles.models import Article
from comments.models import Comment
article = Article.get_by_id(1)
comment = Comment(title="First comment", text="This is first comment")
comment.put()

3)在加载页面时,我希望查看整个数据存储区中所有文章,博客和其他对象的所有注释:

from comments.models import Comment
comments = Commen.all()
for comment in comments:
    # print comment and article title
    print "%s: %s" % (comment.title, comment.object.title)

实际结果:“KindError:没有实施类型'文章'”

预期结果:自动检测对象类型以供参考并加载此类

详情请见:http://code.google.com/p/appengine-framework/issues/detail?id=17
项目需要你的帮助!

2 个答案:

答案 0 :(得分:1)

为了能够返回给定类型的实体,App Engine必须能够为其找到Model类。这样做没有内置机制,因为所有必须查找的是实体类型,可以是任意字符串。

而是导入包含您可能从包含Comment模型的模块引用的模型的模块。这样,只要您可以对Comment执行查询,就会加载所有相关模型。

答案 1 :(得分:0)

在我的项目GAE framework中,我解决了这个问题。在第一页加载时,我已将所有模型加载到内存中。

如果我们的模型具有相同的名称,例如“博客”和“纸板”应用程序中的注释模型,该怎么办?在这种情况下,我们自动为此模型的King模型添加前缀。结果,我们在不同的应用程序中有不同的模型名称:BlogComment和BoardComment。

您可以在源代码中了解更多信息,以了解我们如何执行此实现。