You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django generic.ListView中获取URL参数过滤查询集?

解决Django generic.ListView动态传递项目ID过滤查询集的问题

1. 修改URL路由,添加项目ID参数

先在URL配置中,给MyCentersListView对应的路由添加整数类型的project_id捕获参数:

# urls.py
from django.urls import path
from .views import MyCentersListView

urlpatterns = [
    # 其他路由...
    path('centers/<int:project_id>/', MyCentersListView.as_view(), name='centers_list'),
]

2. 更新模板跳转链接

在MyProjectListView的模板里,修改跳转链接,把当前项目的ID传入URL:

<!-- my_project_list.html -->
{% for project in object_list %}
    <a href="{% url 'centers_list' project.id %}">查看项目{{ project.id }}的所有中心</a>
{% endfor %}

3. 重写ListView的get_queryset方法实现动态过滤

在MyCentersListView中,重写get_queryset方法,从URL参数里获取project_id,用这个值过滤查询集:

# views.py
from django.views.generic import ListView
from .models import Center

class MyCentersListView(ListView):
    model = Center
    template_name = 'my_centers_list.html'
    context_object_name = 'centers'

    def get_queryset(self):
        # 从URL捕获的参数中获取project_id
        project_id = self.kwargs.get('project_id')
        # 存在project_id则返回过滤后的结果,否则返回空集(可根据需求调整)
        if project_id:
            return Center.objects.filter(project_id=project_id)
        return Center.objects.none()

可选:传递当前项目到模板上下文

如果需要在MyCentersListView的模板中显示当前项目信息,可重写get_context_data方法:

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    project_id = self.kwargs.get('project_id')
    from .models import Project
    context['current_project'] = Project.objects.get(id=project_id)
    return context

这样就能根据点击链接时传递的项目ID,动态生成对应的中心查询集了。

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 02:12:47