Google App Engine: realizar consultas complejas

Tengo un modelo como este:

class Person(db.Model):
     ...
     zipcode = db.StringProperty()

class Book(db.Model):
     owner = db.ReferenceProperty(Person)
     date_created = db.DateTimeProperty(auto_add=True)

How can I get a list of all the books within certain zipcode that are sorted by date_created ¿en orden descendente?

preguntado el 25 de septiembre de 13 a las 19:09

2 Respuestas

Taking Greg's answer one step further, the right thing to on App Engine's datastore would be to denormalize:

class Person(db.Model):
     ...
     zipcode = db.StringProperty()

class Book(db.Model):
     owner = db.ReferenceProperty(Person)
     date_created = db.DateTimeProperty(auto_add=True)
     zipcode = db.StringProperty()

You'd have to be careful to set the Book's zipcode when you set the owner. After that it's pretty straightforward to do the query you want as a single query. Greg's solution is more costly since you'll need to do multiple queries and fetch many entities just to do the merge. With large datasets, it's also slow, and you risk various fetch operations timing out, as well as the merge operation taking a long time and a lot of memory.

Respondido el 25 de Septiembre de 13 a las 20:09

You would have to do a query for all Person entities with the zipcode you're looking for, and then lookup each of their books, merge the lists and then sort the result.

Generally, normalisation like you'd do with a relational database won't be the best way to model things with datastore.

Respondido el 25 de Septiembre de 13 a las 19:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.