开发者

How to order by the field stored in the separate model?

开发者 https://www.devze.com 2023-04-13 03:29 出处:网络
Here is simplified version of my datastore structure: class News(db.Model): title = db.StringProperty()

Here is simplified version of my datastore structure:

class News(db.Model):
    title = db.StringProperty()

class NewsRating(db.Model):
    user = db.IntegerProperty()
    rating = db.IntegerProperty()
    news = db.ReferenceProperty(News)

Now I need to display all news sorted by their total rating (sum of different users ratings). How can I do that in the following code:

news = News.all()
# filter by additional parms
# news.filter("city =", "1")
ne开发者_开发百科ws.order("-added") # ?
for one_news in news:
    self.response.out.write(one_news.title()+'<br>')


Queries only have access to the entity you're querying against, if you have a property from another entity (or some aggregate calculation based on fields from other entities) that you want to use to order results, you're going to need to store it in the entity you're querying against.

In the case of ratings, that might mean a periodic task that sums up ratings and distributes them to articles.


To do that you would need to run a query fetching every single NewsRating referencing your News entity and sum all the ratings (as the datastore does not provide JOINs). This will be a huge task both time and cost wise. I'd recommend to take a look at just-overheard-it example as a reference point.

0

精彩评论

暂无评论...
验证码 换一张
取 消