首页 > 解决方案 > 如何使用 Flask 根据用户输入重新排序帖子列表(即新查询)

问题描述

我正在 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 中为这类东西创建菜单,尽管我做了一些搜索。

标签: pythonsqliteflask

解决方案


您可以将查询转换为字典列表,然后使用operator模块的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'}
]

推荐阅读