Django数据库数据过滤:筛选指定类别预约数据并在前端展示
Django 按预约类别筛选数据实现方案
1. 修改视图层代码
改动逻辑:新增类别参数接收与过滤逻辑,合法参数校验避免无效查询,同时将当前选中的类别传入前端用于状态标记。
@login_required(login_url='login') def user(request): appointments = Appointment.objects.all() clients = Client.objects.all() # 新增类别筛选逻辑 ALLOWED_CATEGORIES = ['plumbing', 'electrical', 'cleaning'] current_category = request.GET.get('category', '') # 仅传入合法类别时执行过滤 if current_category in ALLOWED_CATEGORIES: appointments = appointments.filter(category=current_category) # 若需要统计值跟随筛选结果变化,保持以下统计代码位置即可;若要统计全量数据,将其移到筛选逻辑之前 total_appointments = appointments.count() delivered = appointments.filter(status='Delivered').count() pending = appointments.filter(status='Pending').count() context = {'appointments': appointments, 'clients': clients, 'total_appointments': total_appointments, 'delivered': delivered, 'pending': pending, 'current_category': current_category} return render(request, 'users/user.html', context)
2. 修改前端模板代码
改动逻辑:在表格上方新增筛选按钮组,点击自动携带类别参数请求后端,同时根据当前选中状态自动高亮对应按钮,原有表格循环逻辑无需修改。
<!-- 新增筛选按钮组,放在预约表格上方位置即可 --> <div class="btn-group mb-3" role="group"> <a href="?category=" class="btn btn-outline-primary {% if current_category == '' %}active{% endif %}">全部</a> <a href="?category=plumbing" class="btn btn-outline-primary {% if current_category == 'plumbing' %}active{% endif %}">管道维修</a> <a href="?category=electrical" class="btn btn-outline-primary {% if current_category == 'electrical' %}active{% endif %}">电工维修</a> <a href="?category=cleaning" class="btn btn-outline-primary {% if current_category == 'cleaning' %}active{% endif %}">清洁服务</a> </div> <!-- 原有表格渲染逻辑保持不变 --> {% for appointment in appointments %} <tr> <td>{{appointment.worker}}</td> <td>{{appointment.category}}</td> <td>{{appointment.date_created}}</td> <td>{{appointment.status}}</td> <td><a class="btn btn-sm btn-danger" href="{% url 'delete_appointment' appointment.id %}">删除</a></td> </tr> {% endfor %}
内容的提问来源于stack exchange,提问作者David Mutuku
相关产品推荐
相关产品推荐

