Django中实现ChoiceField选项统计及点击跳转功能
实现建筑类型数量展示与跳转功能
1. 更新视图统计各类型房产数量
修改views.py的home视图,统计每个建筑类型下已审核房产的数量,并将数据传递给模板:
from django.db.models import Count from django.db.models import Q def home(request): q = request.GET.get('q') or '' # 保留原有搜索过滤逻辑 props = Property.objects.filter( Q(title__icontains=q) | Q(address__icontains=q) | Q(buildingtype__icontains=q) ) # 统计各建筑类型的已审核房产数量 building_type_counts = Property.objects.filter(is_approved=True)\ .values('buildingtype').annotate(count=Count('id')).order_by() # 将选项与统计结果关联,方便模板调用 building_choices_with_count = [] for choice_value, choice_label in Property.BUILDING_CHOICES: count_data = next((item for item in building_type_counts if item['buildingtype'] == choice_value), None) building_choices_with_count.append({ 'value': choice_value, 'label': choice_label, 'count': count_data['count'] if count_data else 0 }) properties = Property.objects.filter(is_approved=True)[:5] context = { "props": props, "building_choices": building_choices_with_count, "properties": properties } return render(request, "base/index.html", context)
2. 修改首页模板动态渲染类型与跳转链接
替换静态列表为动态循环,渲染所有建筑类型、对应数量,并添加跳转链接(利用现有搜索参数过滤):
<ul class="home4_iconbox mb0"> {% for type in building_choices %} <li class="list-inline-item"> <div class="icon"> <!-- 根据类型匹配对应图标,可根据实际需求调整class --> {% if type.label == 'Storey Building' %} <span class="flaticon-house"></span> {% elif type.label == 'Shop' %} <span class="flaticon-house-1"></span> {% elif type.label == 'Duplex' %} <span class="flaticon-house-2"></span> {% elif type.label == 'Apartment' %} <span class="flaticon-building"></span> {% elif type.label == 'Flat' %} <span class="flaticon-house"></span> {% elif type.label == 'Bungalow' %} <span class="flaticon-house-2"></span> {% elif type.label == 'Warehouse' %} <span class="flaticon-building"></span> {% endif %} <a href="?q={{ type.value }}">{{ type.label }} ({{ type.count }})</a> </div> </li> {% endfor %} </ul>
3. 优化搜索匹配精度(可选)
如果需要避免模糊匹配导致的错误(比如"Shop"匹配到包含该字符串的其他内容),可以将建筑类型的过滤条件改为精确匹配:
props = Property.objects.filter( Q(title__icontains=q) | Q(address__icontains=q) | Q(buildingtype__exact=q) # 精确匹配建筑类型 )
完成以上修改后,首页会自动展示所有建筑类型的已审核房产数量,点击任意类型即可跳转到对应类型的房产列表页面。
内容的提问来源于stack exchange,提问作者Sir Feranmi
相关产品推荐
相关产品推荐

