Thursday, May 28, 2009

Back-references are your friends

A very handy feature of database references is their automatic back-references pairs.

class User(db.Model):
name = db.StringProperty()

class Phone(db.Model):
number = db.PhoneNumberProperty()
user = db.ReferenceProperty(User)

# fetch one user
username = 'John'
user = User().all().filter('name = ', username).get()

# get the first associated phone number for a user
phonenum = user.phone_set[0].number

# list all phone numbers of the user
for phonenum in user.phone_set:
# phonenum here contains the user's actual phonenum in the list

The name of the back-reference property defaults to {model name}+'_set' in lower case, that's how 'phone_set' was made in the example. More about back-references can be read here.



No comments:

Post a Comment