Django实现下拉选择按商品价格高低排序功能的技术咨询
第一步:修改前端模板,增加排序参数提交逻辑
原有select选择器没有触发请求的逻辑,调整代码实现选中排序规则后自动提交参数到后端,同时保留当前分页参数。
- 替换原有sortby区块代码:
<div class="sortby"> <span>Sort By: <select class="sort" onchange="window.location.href = window.location.pathname + '?sort=' + this.value + '&page={{ categories.number }}'"> <option value="highest" {% if request.GET.sort == 'highest' %}selected{% endif %}>最高价格</option> <option value="lowest" {% if request.GET.sort == 'lowest' %}selected{% endif %}>最低价格</option> </select> </span> </div>
- 把模板中遍历商品的语句
{% for product in category.product_set.all %}替换为{% for product in category.sorted_products %},使用后端预处理的排序后商品列表。
第二步:修改视图函数,处理排序逻辑
在视图中获取前端传递的排序参数,给每个分类下的商品做排序处理,修改后的完整视图代码如下:
def waterProducts(request): # 获取排序参数,默认按最低价格排序 sort_type = request.GET.get("sort", "lowest") sort_field = "-price" if sort_type == "highest" else "price" categories = Category.objects.filter( name__startswith="Products").order_by('name') page_num = request.GET.get("page") paginator = Paginator(categories, 3) try: categories = paginator.page(page_num) except PageNotAnInteger: categories = paginator.page(1) except EmptyPage: categories = paginator.page(paginator.num_pages) # 给每个分类添加排序后的商品列表 for cate in categories: cate.sorted_products = cate.product_set.all().order_by(sort_field) if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create( customer=customer, complete=False) items = order.orderitem_set.all() cartitems = order.get_cart_items else: items = [] # 修正原有代码中多余的空格问题 order = {'get_cart_total': 0, 'get_cart_items': 0} cartitems = order['get_cart_items'] waters = Product.objects.all() context = { 'categories': categories, 'waters': waters, 'cartitems': cartitems } return render(request, "products/WaterProductPage.html", context)
内容的提问来源于stack exchange,提问作者JOSEPH MANIA
相关产品推荐
相关产品推荐

