Search code examples
google-app-enginegoogle-cloud-datastoregqlquery

One to Many Database Setup in Google App Engine


class Student(db.Model):
    teacher = db.ReferenceProperty(Teacher, collection_name='students')
    name = db.StringProperty(required=True)
    zip_code = db.IntegerProperty(required=True)
    square_footage = db.IntegerProperty(required=True)
    month_entries = db.IntegerProperty(required=True)  

class Bill(db.Model):
    student = db.ReferenceProperty(Student, collection_name='bills')
    bill_month = db.DateProperty(required=True)
    energy = db.IntegerProperty(required=True)

From my models setup shown above... I can easily show all the Bills stored using something like this:

bill = models.Bill.all()
for stubs in bill:
    print stubs.energy
    print stubs.student.name

But how do I list what Bills each student has? In SQL I would say something like:

SELECT * FROM Bill WHERE Student.Name = Samuel

I guess I don't understand how to retrieve the Bills given by ReferenceProperty. It doesn't seem so simple in GQL. How do I query by Reference Property?


Solution

  • The ReferenceProperty creates an automatic query in the referenced entity (using the collection_name if you provided one, which you did):

    sams_bills = Student.all().filter("name =", "Samuel").get().bills
    

    sams_bills is now a db.Query for the bills, which you can call .fetch() on to retrieve one or more bills.