在Google App Engine中使用Django模板从实体列表中访问具有特定ReferenceProperty值的



我一直在努力解决谷歌应用引擎和Django的问题,并没有能够找到解决方案(尽管发现类似的问题)。

让我来设定一下场景。我有以下三个实体:

Contributor:
    user = db.UserProperty()
Question:
    contributor = db.ReferenceProperty(Contributor, collection_name='questions')
    text = db.TextProperty()
Rating:
    contributor = db.ReferenceProperty(Contributor, collection_name='question_ratings')
    question = db.ReferenceProperty(Question, collection_name='ratings')
    rating = db.IntegerProperty(choices=set([1,2,3,4,5]))

在我的Django模板(如下)中,我的一般要求是显示(1)每个问题,(2)问题的贡献者,(3)问题是否被当前用户评分。

我的问题在于第三个要求。我无法确定Question是否具有与当前User相关的ContributorRating(即具有用户属性users.get_current_user()Contributor)。我怎么才能做到呢?

如果存在这样的Rating实体,将显示类似于"您已经对这个问题进行了评级"的消息。否则,如果不存在这样的Rating,将显示对问题进行评分的选项。这是我的Django模板,满足了前两个需求(还有一个注释概述了第三个需求)。

{% for question in questions %}
    <h1>{{ question.text }}</h1>
    <h2>{{ question.contributor.user.nickname() }}</h2>
    {% comment %}
    if no Rating exists for Question and Contributor:
        <h3>Rating: 1 2 3 4 5</h3>
    else:
        <h3>You have already rated this question.</h3>
    {% endcomment %}
{% endfor %}
下面是Google App Engine的Python处理程序脚本:
questions = Question.all()
ratings = Rating.all()
ratings.filter('contributor = ', profile)
template_values = {
    'contributor': contributor,
    'questions': questions
}
path = os.path.join(os.path.dirname(__file__), "questions.html")
rendered_text = template.render(path, template_values)
self.response.out.write(rendered_text)

最好的方法是在Python代码中进行处理,并将包含相关信息的字典列表传递给Django模板。这也意味着你可以利用像引用属性预取这样的技巧来最小化你必须做的rpc的数量。

最新更新