Flask实战第65天:帖子按照发布时间和评论数量等排序
排序,我们需要在前端传递参数, 编辑front_index.html
编辑front.views.py
from apps.models import HighlightPostModel from sqlalchemy.sql import func ... @bp.route('/') def index(): banners = BannerModel.query.order_by(BannerModel.priority.desc()).all() boards = BoardModel.query.all() # 当前页面 page = request.args.get(get_page_parameter(), type=int, default=1) # 开始位置 start = (page - 1) * config.PER_PAGE # 结束位置 end = start + config.PER_PAGE board_id = request.args.get('bd',type=int, default=None) sort = request.args.get("st", type=int, default=1) query_obj = None if sort == 1: query_obj = PostModel.query.order_by(PostModel.create_time.desc()) elif sort == 2: # 按照加精的时间倒叙排序 query_obj = db.session.query(PostModel).outerjoin(HighlightPostModel).order_by( HighlightPostModel.create_time.desc(), PostModel.create_time.desc()) elif sort == 3: # 按照点赞的数量排序,点赞功能没有做,所以这里用时间倒序排序 query_obj = PostModel.query.order_by(PostModel.create_time.desc()) elif sort == 4: # 按照评论的数量排序 query_obj = db.session.query(PostModel).outerjoin(CommentModel).group_by(PostModel.id).order_by( func.count(CommentModel.id).desc(), PostModel.create_time.desc()) if board_id: query_obj = query_obj.filter(PostModel.board_id == board_id) posts = query_obj.slice(start, end) total = query_obj.count() else: posts = query_obj.slice(start, end) total = query_obj.count() pagination = Pagination(bs_version=3,page=page, total=total) context = { 'banners': banners, 'boards': boards, 'posts': posts, 'pagination': pagination, 'current_board': board_id, 'current_sort': sort } return render_template('front/front_index.html', **context)
排序 功能已经完成了
但是选中的状态样式还没有改,修改front_index.html
每天进步一点,加油!