数据模型是一个很大的主题,但 IMO 有两种方法可供您选择。这对您的问题来说更基本,更具体。它给出了一些想法。
第一种方法——将引用存储为属性
就像考虑产品包含产品变体一样......
这种方法与 RDBMS 世界中的方法类似。您可以单独创建产品,每个产品在每个产品变体中都会有一个参考。它类似于外键在数据库中的工作方式。因此,您将拥有产品变体实体的新属性,其中将包含对其所属产品的引用。产品属性实际上将包含产品种类实体的键。如果这听起来令人困惑,这就是你可以剖析它的方法。我将以python为例:
# product model
class Product(ndb.Model):
name = ndb.StringProperty()
# product variant model
class ProductVariant(ndb.Model):
name = ndb.StringProperty()
price = ndb.IntegerProperty()
# product key.
product = ndb.KeyProperty(kind=Product)
hugoboss = Product(name="Hugo Boss", key=ndb.Key(Product, 'hugoboss'))
gap = Product(name="Gap", key=ndb.Key(Gap, 'gap'))
pants1 = ProductVariant(name="Black panst", price=300, product=hugoboss.key)
pants2 = ProductVariant(name="Grey pants", price=200, product=hugoboss.key)
tshirt = ProductVariant(name="White graphic tshirt", price=10, product=gap.key)
pants1.put()
pants2.put()
tshirt.put()
# so lets say give me all pants that has label hugoboss
for pants in ProductVariant.query(ProductVariant.product == hugoboss.key).fetch(10):
print pants.name
# You should get something:
Black pants
Grey panst
第二种方法——钥匙内的产品
要充分利用它,您需要了解 Bigtable(基于 Bigtable 构建的数据存储)行键的排序功能以及如何围绕它操作数据。如果你想深入了解,这里有很棒的论文Bigtable: A Distributed Storage System for Structured Data
# product model
class Product(ndb.Model):
name = ndb.StringProperty()
# product variant model
class ProductVariant(ndb.Model):
name = ndb.StringProperty()
price = ndb.IntegerProperty()
hugoboss = ndb.Key(Product, 'hugoboss')
gap = ndb.Key(Product, 'gap')
Product(name="Hugo Boss", key=hugoboss).put()
Product(name="Gap", key=gap).put()
pants1 = ProductVariant(name="Black pants", price=300, parent=hugoboss)
pants2 = ProductVariant(name="Grey pants", price=200, parent=hugoboss)
tshirt = ProductVariant(name="White graphic tshirt", price=10, parent=gap)
pants1.put()
pants2.put()
tshirt.put()
# so lets say give me all pants that has label hugoboss
for pants in ProductVariant.query(ancestor=hugoboss).fetch(10):
print pants.name
# You should get something:
Black pants
Grey pants
第二种方法很强大!我希望这会有所帮助。