为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 Flask 根据用户输入重新排序帖子列表(即新查询)

如何使用 Flask 根据用户输入重新排序帖子列表(即新查询)

qq_笑_17 2021-11-02 15:25:34
我正在 Flask 中建立一个网站,并希望让用户能够按照他或她选择的方式对帖子的主列表进行排序。默认情况下,帖子按其“到期日期”升序排列。但是,某些用户可能希望按字母顺序、作者姓名、发布日期等进行排序。一些消息来源建议我根据用户输入构建一个字符串;然而,这似乎不是最有效的方法(也许是!)这是我的代码的样子:@index.route("/")@index.route("/home")def home():    page = request.args.get('page', 1, type=int)    experiences = Exp.query.order_by(Exp.date_expiry.asc()).paginate(page=page, per_page=5)    return render_template('home.html', experiences=experiences)我想我需要将某种变量传递到我的家庭路线中,然后根据它唯一地生成我的查询,我只是不确定最佳实践是什么。另外,我不确定如何在 Flask 中为这类事情创建菜单,尽管我做了一些搜索。
查看完整描述

1 回答

?
MYYA

TA贡献1868条经验 获得超4个赞

您可以将查询转换为字典列表,然后使用运算符模块的itemgetter函数根据一个或多个字典值对条目进行排序。


假设您有以下列表:


posts_list = [

     {'post_id':100, 'author_name': 'John', 'date_posted':'2019-02-14', 'expiry_date':'2019-09-20'},

     {'post_id':101, 'author_name': 'Bob', 'date_posted':'2019-03-15', 'expiry_date':'2019-04-25'},

     {'post_id':102, 'author_name': 'Alice', 'date_posted':'2019-01-16', 'expiry_date':'2019-07-24'},

     {'post_id':103, 'author_name': 'Eric', 'date_posted':'2019-04-14', 'expiry_date':'2019-05-20'}

]

输出按所有字典共有的任何字段排序的这些行非常容易。


例子:


from operator import itemgetter


list_by_author_name = sorted(posts_list, key=itemgetter('author_name'))

list_by_date_posted = sorted(posts_list, key=itemgetter('date_posted'))

list_by_expiry_date = sorted(posts_list, key=itemgetter('expiry_date'))


print(list_by_author_name)

print(list_by_date_posted)

print(list_by_expiry_date)

产生以下结果:


[

{'post_id': 102, 'author_name': 'Alice', 'date_posted': '2019-01-16', 'expiry_date': '2019-07-24'}, 

{'post_id': 101, 'author_name': 'Bob', 'date_posted': '2019-03-15', 'expiry_date': '2019-04-25'}, 

{'post_id': 103, 'author_name': 'Eric', 'date_posted': '2019-04-14', 'expiry_date': '2019-05-20'}, 

{'post_id': 100, 'author_name': 'John', 'date_posted': '2019-02-14', 'expiry_date': '2019-09-20'}

]


[

{'post_id': 102, 'author_name': 'Alice', 'date_posted': '2019-01-16', 'expiry_date': '2019-07-24'}, 

{'post_id': 100, 'author_name': 'John', 'date_posted': '2019-02-14', 'expiry_date': '2019-09-20'}, 

{'post_id': 101, 'author_name': 'Bob', 'date_posted': '2019-03-15', 'expiry_date': '2019-04-25'}, 

{'post_id': 103, 'author_name': 'Eric', 'date_posted': '2019-04-14', 'expiry_date': '2019-05-20'}

]


[

{'post_id': 101, 'author_name': 'Bob', 'date_posted': '2019-03-15', 'expiry_date': '2019-04-25'}, 

{'post_id': 103, 'author_name': 'Eric', 'date_posted': '2019-04-14', 'expiry_date': '2019-05-20'}, 

{'post_id': 102, 'author_name': 'Alice', 'date_posted': '2019-01-16', 'expiry_date': '2019-07-24'}, 

{'post_id': 100, 'author_name': 'John', 'date_posted': '2019-02-14', 'expiry_date': '2019-09-20'}

]


查看完整回答
反对 回复 2021-11-02
  • 1 回答
  • 0 关注
  • 207 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号