如何使用 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 中为这类事情创建菜单,尽管我做了一些搜索。


qq_笑_17
浏览 208回答 1
1回答

MYYA

您可以将查询转换为字典列表,然后使用运算符模块的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 itemgetterlist_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'}]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python