scifirocket
scifirocket

Reputation: 1051

google datastore many to one references

So i have two model classes:

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

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

and then i have a third model class to hold all the pictures

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

Animal is either a Dog or a Cat. Obviously this does not compile.

Now my question is: Is there a way I can put Cat pictures in with Dog pictures? Or do I need to create more models like this:

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

Upvotes: 1

Views: 83

Answers (1)

Nick Johnson
Nick Johnson

Reputation: 101149

You could use PolyModel:

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

class Dog(Animal):
  pass

class Cat(Animal):
  pass

Now you can have a ReferenceProperty that references Animals, and either Dogs or Cats will be permitted.

However, you don't have any properties that are specific to each type of animal - why not just have a regular Animal model, add a property indicating what species it is, and skip the separate models entirely?

Upvotes: 3

Related Questions