5

Say I have the following model:

class Schedule(db.Model):
    tripCode = db.StringProperty(required=True)
    station = db.ReferenceProperty(Station, required=True)    
    arrivalTime = db.TimeProperty(required=True)
    departureTime = db.TimeProperty(required=True)

And let's say I have a Station object stored in the var foo.

How do I assemble a GQL query that returns all Schedule objects with a reference to the Station object referenced by foo?

This is my best (albeit incorrect) attempt to form such a query:

myQuery = "SELECT * FROM Schedule where station = " + str(foo.key())

Once again foo is a Station object

Ryan Delucchi
  • 7,718
  • 13
  • 48
  • 60

2 Answers2

10

You shouldn't be inserting user data into a GQL string using string substitution. GQL supports parameter substitution, so you can do this:

db.GqlQuery("SELECT * FROM Schedule WHERE station = $1", foo.key())

or, using the Query interface:

Schedule.all().filter("station =", foo.key())
Nick Johnson
  • 100,655
  • 16
  • 128
  • 198
  • 2
    FWIW, no need to put foo.key() in the second case. This will work: Schedule.all().filter("station =", foo) – mainsocial Jun 10 '09 at 06:06
7

An even easier thing to do is to change the model definition by adding the 'collection_name' field to the ReferenceProperty:

station = db.ReferenceProperty(Station, required=True, collection_name="schedules")

Then you can just do:

foo.schedules

whenever you want to get all the stations' schedules.

Travis Kriplean
  • 426
  • 5
  • 10