Django:实现get_queryset()的DetailView

时间:2017-07-25 06:44:37

标签: django django-class-based-views django-1.11

我收到以下错误:

ImproperlyConfigured at /elearning/7447932a-6044-498a-b902-97cbdd0a4001/
DetailView is missing a QuerySet. Define DetailView.model, DetailView.queryset, or override DetailView.get_queryset().

关于DetailView上的Django文档,get_query不是必需的,除非我想覆盖它。

view.py

class CourseDetailView(DetailView):

    model = Course
    template_name='elearning/detail.html'

    def get_object(self):
        course = get_object_or_404(Course, pk=self.kwargs['pk'])
        return self.model.objects.filter(pk=pk)

    def get_context_data(self, **kwargs):
        context = super(CourseDetailView, self).get_context_data(**kwargs)
        context['now'] = timezone.now()
        return context

urls.py

url(r'^(?P<pk>[0-9a-z-]+)/$', views.DetailView.as_view(), name='course-detail'),

listview模板

 <a href="{% url 'elearning:course-detail' article.course_id %}">{{ article.title }}</a>

models.py

class Course(models.Model):
    course_id = models.UUIDField(default=uuid.uuid4, editable=False)
    ...

我想知道为什么要实现get_queryset()?

添加get_queryset()

时,我仍然遇到同样的错误
def get_queryset(self):
    qs = super(CourseDetailView, self).get_queryset()
    return qs.filter(pk=self.kwargs['pk'])

2 个答案:

答案 0 :(得分:3)

queryset = Course.objects.all()添加到您的视图中可能值得更加详细并解决错误。

至于def get_queryset(self),您可能希望使用它来对QuerySet执行一些自定义过滤。我将提供一个示例,说明如何使用def get_queryset(self)方法仅返回单本书中的页面。为了完整性,我已经包含了多个url模式,但只包含了实现get_queryset(self)

的相关视图类
# models.py
class Book(models.Model):
    title = models.CharField(max_length=32)

class Page(models.Model):
    book = models.ForeignKey(Book)
    page_num = models.IntegerField()

# views.py
class PageDetailView(DetailView):
    queryset = Page.objects.all()

    def get_queryset(self):
        """Filter pages by a book"""
        return self.queryset.filter(book_id=self.kwargs.get('book_id'))

# urls.py
urlpatterns = [
    url(
        r'^books/$',
        views.BookListView.as_view(),
        name='book-list',
    ),
    url(
        r'^books/(?P<pk>\d+)/$',
        views.BookDetailView.as_view(),
        name='book-detail',
    ),
    url(
        r'^books/(?P<book_id>\d+)/pages/$',
        views.PageListView.as_view(),
        name='page-list',
    ),
    url(
        r'^books/(?P<book_id>\d+)/pages/(?P<pk>\d+)/$',
        views.PageDetailView.as_view(),
        name='page-detail',
    ),
]

答案 1 :(得分:2)

您的观点的名称为CourseDetailView,但您在网址中使用DetailView

url(r'^(?P<pk>[0-9a-z-]+)/$', views.DetailView.as_view(), name='course-detail'),

所以网址将是

url(r'^(?P<pk>[0-9a-z-]+)/$', views.CourseDetailView.as_view(), name='course-detail'),