📝 Django

Overriding get_queryset in Django CBVs

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
78
🌳
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

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 138
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 91
📝

HTML Lists

Lists are one of the most common markup elements. Navigation menus, post tags, how-to steps,...

📅 30.06.2026 👁️ 90

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!