【问题标题】:google datastore many to one references谷歌数据存储多对一引用
【发布时间】:2011-10-03 07:42:41
【问题描述】:

所以我有两个模型类:

class Dog(db.model):
   dogName = StringProperty()
   dogBreed = StringProperty()

class Cat(db.model):
   catName = StringProperty()
   catBreed = StringProperty()

然后我有第三个模型类来保存所有图片

class Images(db.model):
  imageReference = ReferenceProperty(*Animal*, collection_name = 'allImages')
  imageURL = StringProperty()

动物要么是狗,要么是猫。显然这不会编译。

现在我的问题是:有没有办法可以将猫的照片和狗的照片放在一起?还是我需要创建更多这样的模型:

class DogImages(db.model):
  imageReference = ReferenceProperty(Dog, collection_name = 'allImages')
  imageURL = StringProperty()
class CatImages(db.model):
  imageReference = ReferenceProperty(Cat, collection_name = 'allImages')
  imageURL = StringProperty()

【问题讨论】:

    标签: google-app-engine data-modeling google-cloud-datastore


    【解决方案1】:

    你可以使用PolyModel:

    class Animal(polymodel.PolyModel):
      name = db.StringProperty()
      breed = db.StringProperty()
    
    class Dog(Animal):
      pass
    
    class Cat(Animal):
      pass
    

    现在您可以拥有一个引用动物的 ReferenceProperty,并且允许使用 Dogs 或 Cats。

    但是,您没有任何特定于每种动物的属性 - 为什么不只拥有一个常规的 Animal 模型,添加一个指示它是什么物种的属性,然后完全跳过单独的模型?

    【讨论】:

    • 狗和猫只是我编造的玩具例子。实际上,模型具有许多属性,并且其中很多是不同的。所以我不知道这是否是我想要使用的东西。
    • @scifirocket 在这种情况下,您可能有一个很好的 Polymodel 用例。但是,如果您的玩具示例在您的真实代码中反映了影响您做出决定的问题,那么将来它会有所帮助。 :)
    • 你是对的。 Polymodels 似乎是我正在寻找的完美匹配。谢谢!
    猜你喜欢
    • 2013-05-17
    • 2014-10-21
    • 1970-01-01
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 2014-10-30
    • 2017-12-24
    • 1970-01-01
    相关资源
    最近更新 更多