基于URL参数过滤Django Queryset

时间:2016-03-31 19:39:48

标签: django django-models django-templates django-views

我有两个型号 - 一个用于工具,一个用于零件。列表页面将完全相同。我可以根据网址过滤模板中显示的内容吗?

观看次数 (我希望将tool_list和part_list合并到product_list中)

def tool_list(request):
    tools = Tool.objects.all()
    parts = Part.objects.all()
    return render(request, 'tool_list.html', {'tools': tools, 'parts': parts})


def part_list(request):
    parts = Part.objects.all()
    tools = Tool.objects.all()
    return render(request, 'tool_list.html', {'parts': parts, 'tools': tools})


def product_detail(request, **kwargs):
    tool = get_object_or_404(Tool,  slug=kwargs.get('slug'))
    part = get_object_or_404(Part)
    return render(request, 'product_detail.html', {'tool': tool, 'part': part})

网址

urlpatterns = [
    url(r'^products/tools/$', tool_list, name='tool_list'),
    url(r'^products/parts-supplies/$', part_list, name='part_list'),
    url(r'^products/(?P<category>[^\.]+)/(?P<slug>[^\.]+)/$', product_detail, name='product_detail'),
]

1 个答案:

答案 0 :(得分:1)

您的两个观点tool_listpart_list是彼此的精确复制品。您可以创建单个视图并将多个URL路由到该视图。喜欢这个

def product_list(request):
    tools = Tool.objects.all()
    parts = Part.objects.all()
    return render(request, 'tool_list.html', {'tools': tools, 'parts': parts})

在你的网址中:

url(r'^products/tools/$', product_list, name='tool_list'),
url(r'^products/parts-supplies/$', product_list, name='part_list'),