๐Ÿ“ Django

Overriding get_queryset in Django CBVs

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
275
๐ŸŒณ
Level
Advanced

get_queryset() is a method for customizing the dataset used in a CBV.

Filtering by the current user

from django.views.generic import ListView
from django.contrib.auth.mixins import LoginRequiredMixin
from .models import Task

class MyTaskListView(LoginRequiredMixin, ListView):
    model = Task
    template_name = 'tasks/my_tasks.html'

    def get_queryset(self):
        return Task.objects.filter(owner=self.request.user)

Filtering from GET parameters

class TaskListView(ListView):
    model = Task

    def get_queryset(self):
        qs = Task.objects.all()
        status = self.request.GET.get('status')
        if status:
            qs = qs.filter(status=status)
        q = self.request.GET.get('q')
        if q:
            qs = qs.filter(title__icontains=q)
        return qs.order_by('-created_at')

Depending on URL parameters

# URL: /projects/<pk>/tasks/
class ProjectTaskListView(ListView):
    model = Task

    def get_queryset(self):
        project_pk = self.kwargs['pk']
        return Task.objects.filter(
            project__pk=project_pk,
            owner=self.request.user,
        )

DetailView โ€” restricting access

class TaskDetailView(LoginRequiredMixin, DetailView):
    model = Task

    def get_queryset(self):
        # Returns 404 if the task does not belong to the user
        return Task.objects.filter(owner=self.request.user)

vs get_context_data

Method Purpose
get_queryset() Define the set of objects to display
get_context_data() Add extra variables to the template

get_queryset() runs before get_context_data() โ€” its result is available via self.object_list or self.object.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 316
๐Ÿ“

DRF ViewSets and Routers

ViewSet is a class that combines several related views into one. Router automatically generates URLs.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 285
๐Ÿ“

Django: Production Checklist

Before deploying a Django project, review its security, database, static files, HTTPS, logging, and backup...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 295
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

Django RequestLab: from HTTP to secure production Open course curriculum