首先,要澄清一下,实体祖先不是建立关系所必须的(它有一些缺点),请参见您能帮助我理解nbd密钥类文档还是祖先关系?。和数据存储区中的相关祖先关系
您需要考虑与Google Cloud Datastore平衡强大和最终的一致性。
其余答案假定未使用任何实体血统。
要将产品与类别(或多个,如果需要,可以使用重复属性)相关联,您可以:
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()
这种方法存在可伸缩性问题:如果产品分为多个类别,则更新类别列表的速度将变得越来越慢(整个实体不断增长,每次都需要重新编写),并且如果对属性进行索引,则它很敏感。在爆炸索引问题。
通过将产品类别关系存储为单独的实体可以避免这种情况:
class ProductCategory(ndb.Model):
product = ndb.KeyProperty(kind='Product')
category = ndb.KeyProperty(kind='Category')
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])))