【发布时间】:2013-05-21 14:20:19
【问题描述】:
我正在学习在 GAE 中工作。我已经阅读了很多论文,所有来自 Google 的 NDB 文档和一些问题。我已经习惯了 SQL,但是将过去 20 年的思维方式转变为 NoSQL 对我来说有点困难,而且这里给出的所有这些不同的解决方案都让我抓狂。
我有下一个简单的结构: BOOKS 不能有 CHAPTERS 可以投票的章节 例如,《哨兵》一书可以有 3 个章节,每个章节分别有 0、8 和 12 个投票。
在传统的 SQL 中,我只创建从 VOTES 到 CHAPTERS 和 BOOKS 以及从 CHAPTERS 到 BOOKS 的外键。
我为我的模型这样做:
class Book(ndb.Model):
title = ndb.StringProperty(required=True)
author = ndb.StringProperty(required=True)
created = ndb.DateTimeProperty(auto_now_add=True)
# Define a default ancestor for all the books
@staticmethod
def bookKey(group='books'):
return ndb.Key(Book, group)
# Search all
@classmethod
def getAll(cls):
q = Book.query(ancestor=cls.bookKey())
q = q.order(Book.title)
books = q.fetch(100)
return books
@classmethod
def byId(cls, id):
book = Book.get_by_id(long(id), cls.bookKey())
# Get all the Chapters for a book
def getChapters(self):
chapters = Chapter.query(ancestor=self).order(Chapter.number).fetch(100)
return chapters
class Chapter(ndb.Model):
""" All chapters that a book have """
title = ndb.StringProperty(required=True)
number = ndb.IntegerProperty(default=1)
created = ndb.DateTimeProperty(auto_now_add=True)
book = ndb.KeyProperty(kind=Book)
# Search by Book (parent)
@classmethod
def byBook(cls, book, limit=100):
chapter = book.getChapters()
return chapter
# Search by id
@classmethod
def byId(cls, id, book):
return Chapter.get_by_id(long(id), parent=book)
class Vote(ndb.Model):
""" All votes that a book-chapter have """
value = ndb.IntegerProperty(default=1)
book = ndb.KeyProperty(kind=Book)
chapter = ndb.KeyProperty(kind=Chapter)
好吧,我的疑问是:
- 这种方法正确吗?
- 我创建的函数 bookKey() 最好有一个“虚拟祖先”以确保所有实体都使用祖先?
- 我必须在 Vote 类中为一本书和一章定义一个引用,因为它是一个外键(就像我认为我所做的那样)?
- 是否明确定义了从书中检索章节的方式?我的意思是,在 Chapter 类中,函数 byBook 使用了 Book 类中的函数。或者我必须避免使用其他实体的函数来获得更简洁的代码吗?
- 如何检索某一章节的所有投票?
- 获取特定章节和特定书籍的所有投票总和的正确方法是什么?
最后,我将展示一个包含我所有书籍的表格。在表格中,我想获得每本书的所有投票的总和。例如:
姓名 |投票 哨兵 | 30 票 女巫 | 4 票
我如何获得这些信息,尤其是计票。
然后,点击书名,我想显示他所有的章节(我想那时我必须在章节模型上使用 byBook 功能,对吧?)。
获取此类数据需要哪个 GQL?
提前致谢。
【问题讨论】:
标签: python google-app-engine app-engine-ndb