Reputation: 20310
I have a model like this:
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
in descending order?
Upvotes: 0
Views: 61
Reputation: 15143
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.
Upvotes: 1
Reputation: 10360
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.
Upvotes: 0