问题
I only want that someone confirm me that I'm doing things in the right way.
I have this structure: Books that have Chapters (ancestor=Book) that have Pages (ancestor=Chapter)
It is clear for me that, to search for a Chapter by ID, I need the book to search by ancestor query.
My doubt is: do I need all the chain book-chapter to search a page?
For example (I'm in NDB):
class Book(ndb.Model):
# Search by id
@classmethod
def by_id(cls, id):
return Book.get_by_id(long(id))
class Chapter(ndb.Model):
# Search by id
@classmethod
def by_id(cls, id, book):
return Chapter.get_by_id(long(id), parent=book.key)
class Page(ndb.Model):
# Search by id
@classmethod
def by_id(cls, id, chapter):
return Page.get_by_id(long(id), parent=chapter.key)
Actually, when I need to search a Page to display its contents, I'm passing the complete chain in the url like this:
getPage?bookId=5901353784180736&chapterId=5655612935372800&pageId=1132165198169
So, in the controller, I make this:
def get(self):
# Get the id parameters
bookId = self.request.get('bookId')
chapterId = self.request.get('chapterId')
pageId = self.request.get('pageId')
if bookId and chapterId and pageId:
# Must be a digit
if bookId.isdigit() and chapterId.isdigit() and pageId.isdigit():
# Get the book
book = Book.by_id(bookId)
if book:
# Get the chapter
chapter = Chapter.by_id(chapterId, book)
if chapter:
# Get the page
page = Page.by_id(pageId, chapter)
Is this the right way? Must I have always the complete chain in the URL to get the final element of the chain?
If this is right, I suppose that this way of work, using NDB, does not have any impact on the datastore, because repeated calls to this page always hit the NDB cache for the same book, chapter and page (because I'm getting by id, is not a fetch command). Is my suppose correct?
回答1:
No, there's no need to do that. The point is that keys are paths: you can build them up dynamically and only hit the datastore when you have a complete one. In your case, it's something like this:
page_key = ndb.Key(Book, bookId, Chapter, chapterId, Page, pageId)
page = page_key.get()
See the NDB docs for more examples.
来源:https://stackoverflow.com/questions/16830697/working-with-ancestors-in-gae