Menu
CoddyTech

Filtering With get_queryset

Part of the Class-Based Views section of Coddy's Django journey. Lesson 7 of 18.

The jobs page now has city links like ?city=Berlin, and they change nothing. The part of a URL after ? is the query string, and Django puts it in request.GET.

A ListView gets its rows from a method, get_queryset(). Override it to choose them. A recipe site lists only quick recipes when the URL has ?quick=1:

class RecipeListView(ListView):
    model = Recipe
    ordering = ["title"]

    def get_queryset(self):
        recipes = super().get_queryset()
        if self.request.GET.get("quick"):
            recipes = recipes.filter(minutes__lte=30)
        return recipes

In a class-based view the request is self.request. super().get_queryset() is every row, already sorted by ordering. self.request.GET.get("quick") is a string, or None when the URL has no such key, so the page without a query string still lists everything.

challenge icon

Challenge

Easy

Make the city links work. In JobListView, override get_queryset():

  • ?city=Lisbon lists only the jobs in Lisbon.
  • With no city, every job.
  • Either way, the newest job first.

Press Run, open /jobs/ and click Lisbon.

Try it yourself

from django.views.generic import DetailView, ListView, TemplateView

from .models import Job


class HomeView(TemplateView):
    template_name = "jobs/home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["count"] = Job.objects.count()
        context["latest"] = Job.objects.order_by("-posted").first()
        return context


class AboutView(TemplateView):
    template_name = "jobs/about.html"


class JobListView(ListView):
    model = Job
    context_object_name = "jobs"
    ordering = ["-posted"]


class JobDetailView(DetailView):
    model = Job
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Class-Based Views

Practice on your own: Django playground