【发布时间】:2014-08-22 16:19:23
【问题描述】:
假设我有两个数据存储模型:
class Author(ndb.Model):
name = ndb.StringProperty()
has_dog = ndb.BooleanProperty(default = False)
class Book(ndb.Model):
title = ndb.StringProperty()
author_key = ndb.KeyProperty() # key of associated Author entity
创建Book 实体时,会为其author_key 分配Author 实体的键。现在,我可以像这样查询每个作者的书籍列表:
books_per_author = Book.query(Book.author_key == author_key).fetch()
...然后像这样在 jinja 模板上渲染它们:
{% for book in books_per_author %}
<h2>{{book.title}}</h2>
{% endfor %}
但是如果我还想在同一个模板中显示作者的has_dog 值怎么办?也许我可以像这样将数据标准化为Book 实体:
class Book(ndb.Model):
title = ndb.StringProperty()
author_key = ndb.KeyProperty()
author_has_dog = ndb.BooleanProperty() # get this value from Author entity before book.put() happens
所以现在,当我们创建 Book 实体时,我们只需获取 Author 的 has_dog 值并将其保存在 Book 的 author_has_dog 属性中。问题解决了,我们可以这样做:
{% for book in books_per_author %}
<h2>{{book.title}}</h2>
<div>Has dog: {{book.author_has_dog}}</div>
{% endfor %}
问题:现在,如果我们突然改变Author 实体中has_dog 的值怎么办?我们如何有效地更改与该作者关联的许多 Book 实体中的 author_has_dog 值?
编辑以包含NewBook处理程序:
class NewBook(BaseHandler):
def get(self):
title = self.request.get('title')
author_key = self.get_author_key()
self.render('booklist-per-author.html', title = title, author_key = author_key)
【问题讨论】:
标签: python google-app-engine jinja2 google-cloud-datastore app-engine-ndb