gglasses
gglasses

Reputation: 876

Django: trying to understand how the queryset attribute works in class-based generic views

When using class-based generic views in Django, having a queryset attribute means to "restrict" the collection of object the view will operate on, right?

If queryset is provided, that queryset will be used as the source of objects. (Django's get_object())

Model:

from django.db import models

class Person(models.Model):
    full_name = models.CharField(max_length=30)
    is_active = False

View:

from django.views.generic import DetailView
from books.models import Person

class PersonDetail(DetailView):
    queryset = Person.objects.filter(is_active=True)

The queryset above makes sure to only consider objects with is_active=true.

But how does this works internally?

For example: Does Django appends a SQL condition AND is_active=TRUE to every query in the view?

Ok that last example seems pretty stupid but I hope you get the idea of my question. Thank you.

Upvotes: 0

Views: 224

Answers (1)

solarissmoke
solarissmoke

Reputation: 31414

Yes, this is exactly what happens. Your queryset is used as the base queryset by the view's get_object method. It then applies an additional filter to get a specific object (e.g., by ID):

queryset = queryset.filter(pk=pk)

Of course, the view needs a single object, not a queryset, so it then does:

obj = queryset.get()

Which will either return a single object, or a DoesNotExist or MultipleObjectsReturned exception. DoesNotExist results in a 404. MultipleObjectsReturned is unhandled and will propagate to your code.

Upvotes: 2

Related Questions