Saturday, January 22, 2011

Modeling collections in Google App Engine

When I first began working with Google App Engine I assumed I would need to model a one-to-many relationship manually with a db.ReferenceProperty in each of the manies and db.ListProperty(db.ReferenceProperty) on the one. The actual solution is much simpler and elegant:

class StackUserData(db.Model):
    name = db.StringProperty()
    last_access = db.IntegerProperty()

class Activity(db.Model):
    user = db.ReferenceProperty(StackUserData,
                                collection_name='activities')
    title = db.StringProperty()
    body = db.StringProperty(default='')
    link = db.LinkProperty()
    creation_date = db.IntegerProperty()
    last_activity_date = db.IntegerProperty()

This adds an activities attribute to StackUserData behind the scenes. So StackUserData.activities will give you a list of all activities owned by that StackUserData instance. This relationship is set when creating the Activity:

Activity(user = activity_owner_user).put()

This code will create a new Activity and attach it to the activity_owner_user.

Find out more at Datastore series: Modeling Entity Relationships

No comments:

Post a Comment