0

我正在使用 Django v1.4,并且正在尝试对通用 ListView 视图进行子类化。这是代码

from django.views.generic import ListView

class SearchListView(ListView):
    model = None
    fields = None

    def get_queryset(self):
        #...etc...
        return super(SearchListView, self).get_queryset()

然后,我将为特定模型进一步定制该视图:

class PersonSearchListView(SearchListView):
    model = Person
    fields = ['first_name', 'last_name']

所以发生的情况是,ImproperlyConfigured 异常是超类 (ListView),说明应该定义模型或查询集。我以为我是……(模型=人)。为什么这个值没有进入视图?

谢谢

4

1 回答 1

0

你打电话时super(SearchListView, self).get_queryset()

您将调用以下类的 get_queryset,如您所见,如果您未设置模型或查询集,它将引发异常。

ListView 是 MultipleObjectMixin 的子视图。

但是如果你实例化一个 PersonSearchListView,那么模型应该已经被正确设置了。你能包括url配置吗?稍后会尝试并更新我的答案。

class MultipleObjectMixin(ContextMixin):
    """
    A mixin for views manipulating multiple objects.
    """
    allow_empty = True
    queryset = None
    model = None
    paginate_by = None
    context_object_name = None
    paginator_class = Paginator

    def get_queryset(self):
        """
        Get the list of items for this view. This must be an iterable, and may
        be a queryset (in which qs-specific behavior will be enabled).
        """
        if self.queryset is not None:
            queryset = self.queryset
            if hasattr(queryset, '_clone'):
                queryset = queryset._clone()
        elif self.model is not None:
            queryset = self.model._default_manager.all()
        else:
            raise ImproperlyConfigured("'%s' must define 'queryset' or 'model'"
                                       % self.__class__.__name__)
        return queryset
于 2012-09-26T03:40:02.453 回答