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

萝らか妹 提交于 2019-12-12 05:39:41

问题


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")
news.order("-added") # ?
for one_news in news:
    self.response.out.write(one_news.title()+'<br>')

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7784808/how-to-order-by-the-field-stored-in-the-separate-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!