剩下的答案假设没有使用实体祖先。在
要将一个产品与一个类别(或多个类别,如果需要,可以使用repeated properties)关联,可以使用:class Product(ndb.Model):
name = ndb.StringProperty()
category = ndb.KeyProperty(kind='Category', repeated=True)
category = ndb.Key("Category", "Books")
new_product = Product(title="Coding Horrors Book",
category=[category]).put()
这种方法有一个可伸缩性问题:如果一个产品属于许多类别,那么更新类别列表会变得越来越慢(整个实体,逐渐增长,每次都需要重新编写),而且,如果属性被索引,它对exploding indexes problem敏感。在
这可以通过将产品类别关系存储为单独的实体来避免:
^{pr2}$
可伸缩性更好,但在本例中,您需要一个ProductCategory查询来确定产品的相关类别实体的键,然后进行键查找以获取这些类别的详细信息,大致如下:category_keys = ProductCategory.query(ProductCategory.product == product_key) \
.fetch(keys_only=True, limit=500)
if category_keys:
categories = ndb.get_multi(category_keys)
logging.info('product %s categories: %s' \
% (product.title, ','.join([c.name for c in categories])))