views:

41

answers:

1

Let's say I have a datastore that contains mother, father, and child objects. Inside the Mother and Father objects I have a field called child which stores a reference to their child. Is it possible to reference this child from both mother and father without creating duplicate child instances for each (in the style of OOP). Is this how databases work at all?

+5  A: 

Yes, you can use the db.ReferenceProperty to do exactly that.

A reference property simply stores the unique key of the entity it references. So the mother and father entities could each contain a copy of the key corresponding to their child like this:

class Child(db.Model):
    ... # child properties
class Father(db.Model):
    child = db.ReferenceProperty(Child)
    ...
class Mother(db.Model):
    child = db.ReferenceProperty(Child)
    ...
David Underhill
Here's a follow-up question. Let's assume now that the mother and father store a list of child objects (children). Since a list is expandable, I cannot represent each child as its own instance variable (like: child_x = db.ReferenceProperty(Child). How would I store a list of references to Child objects?
You can use [db.ListProperty](http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#ListProperty) to store a list of [db.Key](http://code.google.com/appengine/docs/python/datastore/keyclass.html)s which each refer to a `Child` entity. Read more about it [here](http://code.google.com/appengine/docs/python/datastore/entitiesandmodels.html#Lists).
David Underhill
Thanks a lot for the help!