big*_*801 1 python mysql sql django
我在转换编写正确的Python脚本时遇到了麻烦,该脚本完成了我能完成的任务 MYSQL
下面是完成我想要的SQL查询.我python在GROUP BY声明中被绊倒的地方.
SELECT COUNT(story_id) AS theCount, `headline`, `url` from tracking
GROUP BY `story_id`
ORDER BY theCount DESC
LIMIT 20
Run Code Online (Sandbox Code Playgroud)
这是我python到目前为止所拥有的.这可以很好地查询所有文章,但它缺少任何类型groupby()或order_by()基于COUNT.
articles = ArticleTracking.objects.all().filter(date__range=(start_date, end_date))[:20]
article_info = []
for article in articles:
this_value = {
"story_id":article.story_id,
"url":article.url,
"headline":article.headline,
}
article_info.append(this_value)
Run Code Online (Sandbox Code Playgroud)
小智 8
正确的方法是使用聚合.
articles = ArticleTracking.objects.filter(date__range=(start_date, end_date))
articles = articles.values('story_id', 'url', 'headline').annotate(count = Count('story_id')).order_by('-count')[:20]
Run Code Online (Sandbox Code Playgroud)
另请阅读Django中的聚合文档.
https://docs.djangoproject.com/en/dev/topics/db/aggregation/
| 归档时间: |
|
| 查看次数: |
5629 次 |
| 最近记录: |