当我编辑一本书时,如何在不提及“当前”作者的情况下更改作者?
您可以在保存实体之前使用ndb.Model.allocate_ids 保留密钥
我是否需要在 Book 上添加与 KeyProperty 的反向关系?
根据您的模型,添加反向查找键可以让您的生活更轻松
如果一本书被删除了怎么办?作者的书单中会有一个 None 值。我必须删除它吗?
Auther.books 中的键在这种情况下不会自动变为 null。您必须自己删除它。
我正在使用重复的 KeyProperty,因为这使得订购书籍变得容易,这对我来说很重要。
一个潜在的问题是实体的大小限制为 1mb。如果作者是多产的作家(例如 Edwy Searles Brooks 已发表 800 多部作品),则可能会超出限制。
我会这样设计模型:
class Author(ndb.Model):
name = ndb.StringProperty()
class Book(ndb.Model):
authors = ndb.KeyProperty('Author', required=True) # Usually it is at most a couple of authors
title = ndb.StringProperty()
要查找由 id 为 1234 的特定作者撰写的所有书籍,您可以
Book.query(Book.authors == ndb.Key('Author', 1234)).fetch()
显然书籍的排序必须明确存储,我建议第三方实体跟踪此信息:
class BookList(ndb.Model):
name = ndb.StringProperty()
book_keys = ndb.KeyProperty(kind='Book', repeated=True)
那么你就可以用这种方式取书了
stephen_king_book_list = stephen_king_book_list_key.get()
books = ndb.get_multi(stephen_king_book_list.book_keys)
# Some of key can lead to None if the underlying book is already deleted
# You can define some background job to sweep clean the list from time to time
# But let filter out the bad guys first
books = [b for b in books if b]
如果您认为您的列表会非常长,您可以将列表分解为链表结构等片段
class BookList(ndb.Model):
prev_segment = ndb.KeyProperty(kind='BookList', required=False)
next_segment = ndb.KeyProperty(kind='BookList', required=False)
name = ndb.StringProperty()
book_keys = ndb.KeyProperty(kind='Book', repeated=True)
您可以通过以下方式轻松找到第一个片段:
starting_point = BookList.query(BookList.name == 'Stephen_King',
BookList.prev_segment == None
).fetch()
当然,如果插入非常频繁,您可能希望使用另一种结构来保存图书列表