Umur Kontacı
Umur Kontacı

Reputation: 35478

django's generic view problem (detailview, get_queryset)

Generic views exist to make our lifes easier, but the time spent on understanding how these stuff work makes them harder actually. Maybe it's me but I've trying to figure how to fix this for a long time that I could write the view myself easily and move on but I insisted on learning it.

I want a custom DetailView class to be shown, the code throws:

'Sculpture' object has no attribute 'filter'

from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from sculptures.models import Sculpture

class SculptureListView(ListView):
    """docstring for SculptureListView"""
    def get_queryset(self):
        return Sculpture.objects.all() 
class SculptureDetailView(DetailView):
    """docstring for SculptureDetailView"""
    def get_queryset(self):
        sculpture = get_object_or_404(Sculpture, slug=self.kwargs['slug'])
        return sculpture

I know it requires one line fix -- at most but couldn't figure out.

And ideas?

Upvotes: 1

Views: 2488

Answers (2)

Thai Tran
Thai Tran

Reputation: 9935

to return a single object, use get_object

class SculptureDetailView(DetailView):
    """docstring for SculptureDetailView"""
    def get_object(self):
        sculpture = get_object_or_404(Sculpture, slug=self.kwargs['slug'])
        return sculpture

Upvotes: 5

Daniel Roseman
Daniel Roseman

Reputation: 599610

get_queryset, as the name implies, should return a Queryset, not a single object.

Upvotes: 8

Related Questions