Django:DetailView 实现 get_queryset()

Django: DetailView implementing a get_queryset()

我收到以下错误:

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'),

列表视图模板

 <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'])

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

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

的相关视图 class
# 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',
    ),
]

您的视图名为 CourseDetailView,但您在 url

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

所以 url 将是

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