如何按单独模型中存储的字段进行排序?
这是我的数据存储结构的简化版本:
class News(db.Model):
title = db.StringProperty()
class NewsRating(db.Model):
user = db.IntegerProperty()
rating = db.IntegerProperty()
news = db.ReferenceProperty(News)
现在我需要显示按总评分(不同用户评分的总和)排序的所有新闻。我怎样才能在下面的代码中做到这一点:
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>')
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>')
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查询只能访问您正在查询的实体,如果您有另一个实体的属性(或基于其他实体的字段的某些聚合计算),您想要用于对结果进行排序,则需要存储它位于您要查询的实体中。
就评级而言,这可能意味着一项定期任务,该任务总结评级并将其分配给文章。
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.
为此,您需要运行一个查询来获取引用您的
News
实体的每个NewsRating
并对所有评级求和(因为数据存储区不提供 JOIN)。这将是一项艰巨的任务,无论是时间还是成本。我建议您查看只是- Overheard-it 示例作为参考点。To do that you would need to run a query fetching every single
NewsRating
referencing yourNews
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.