userBG
userBG

Reputation: 7180

How do I order by date when using ReferenceProperty?

I have a simple one-to-many structure like this:

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

class Comment(db.Model):
    user = db.ReferenceProperty(User, collection_name="comments")
    comment = db.StringProperty()
    date = db.DateTimeProperty()

I fetch a user from by his email:

q = User.all() # prepare User table for querying
q.filter("userEmail =", "[email protected]")  # apply filter, email lookup
results = q.fetch(1) # execute the query, apply limit 1
the_user = results[0] # the results is a list of objects, grab the first one

this_users_comments = the_user.comments # get the user's comments

How can I order the user's comments by date, and limit it to 10 comments?

Upvotes: 0

Views: 86

Answers (2)

ribrdb
ribrdb

Reputation: 459

That query fetches the user. You need to do another query for the comments: this_users_comments.order('date').limit(10) for comment in this_users_comments: ...

Upvotes: 0

HardlyKnowEm
HardlyKnowEm

Reputation: 3232

You will want to use the key keyword argument of the built-in sorted function, and use the "date" property as the key:

import operator
sorted_comments = sorted(this_users_comments, key=operator.attrgetter("date"))
# The comments will probably be sorted with earlier comments at the front of the list
# If you want ten most recent, also add the following line:
# sorted_comments.reverse()
ten_comments = sorted_comments[:10]

Upvotes: 2

Related Questions