Charles Smith
Charles Smith

Reputation: 3289

Filter Django Queryset Based on URL Parameter

I have two models - one for tools and one for parts. The list page will be identical. Can I filter what is shown in the template based on URL?

Views (I'd like to combine tool_list and part_list into 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})

url

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'),
]

Upvotes: 0

Views: 293

Answers (1)

v1k45
v1k45

Reputation: 8250

Your two views, tool_list and part_list are exact replicas of each other. You can create a single view and route multiple urls to it. Like this

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

In your urls:

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

Upvotes: 1

Related Questions