簡體   English   中英

如何使用Flask根據用戶輸入對帖子列表(即新查詢)進行重新排序

[英]How to reorder list of posts (i.e., new query) based on user input with 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中為這種事情創建菜單,盡管我在周圍搜索了一些東西。

您可以將查詢轉換為詞典列表,然后使用操作員模塊的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'}
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM