sqlalchemy + flask ,按天获取所有帖子 [英] sqlalchemy + flask , getting all post by day

查看:37
本文介绍了sqlalchemy + flask ,按天获取所有帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子,posts.

其中包括:

id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(200))
content =  db.Column(db.Text())
time = db.Column(db.DateTime)

当我导航到这个 url 时,这就是我想要实现的目标.

this is what I am trying to achieve when I navigate to this url.

/allposts

posts on 01-01-2013
 - post 1
 - post 2
 - post 3 

posts on 01-02-2013
 - post 4
 - post 5
 - post 6

等等.

我尝试过 group by 但我无法实现我上面解释的内容.

I have tried group by but I couldn't achieve what I explained above.

我正在使用 sqlalchemy 和 Flask python 框架.

I am using sqlalchemy and flask python framework.

同时提供原始查询和 sqlalhemy 查询会好得多,因此我可以在这里概括一些概念.

providing both , raw and sqlalhemy queries will be much better so I can wrap my head around some of the concepts here.

谢谢!

推荐答案

我不会在查询中这样做,而是在 python 端创建所需的分组:

I would not do it in a query, but rather create desired grouping on the python side:

# get desired posts (add your filters etc)
posts = session.query(Post).order_by(Post.time)

# create a dictionary, where key is the date(-only), and values are the posts of that day
from collections import defaultdict
grouped = defaultdict(list)
for post in posts:
    dat = post.time.date()
    grouped[dat].append(post)

# iterate over new grouped structure
for dat, posts in sorted(grouped.items()):
    print dat
    for post in posts:
        print '  ', post

这篇关于sqlalchemy + flask ,按天获取所有帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆