django:为什么空的queryset会触发NoReverseMatch异常?

时间:2016-01-29 14:01:20

标签: python django django-queryset

模型的url模式如下所示:

url(r'^models/(?P<pk>\d+)/$', views.ThreediModelView.as_view(), 
    name='models'),

只要将现有的pk传递给我的get_queryset()方法,我就会获得有效的响应。将不存在的ID传递给视图后,

NoReverseMatch at /models/models/9999/

异常被抛出。我真的不明白为什么。是不是允许返回空的查询集?如果对象列表为空,我不会在我的模板中明确检查。

查看

class ThreediModelView(LoginRequiredMixin, ListView):
    """
    Return a ThreediModel queryset, possibly filtered
    """

    model = ThreediModel
    template_name = 'models.html'
    context_object_name = 'threedi_models'
    search_fields = ["display_name", "slug", "status"]
    search_paceholder = SEARCH_PLACEHOLDER
    # default empty search
    search_str_raw = ""

    def get_queryset(self):
        """
        :return: ThreediLog entries per revision. revision hash can
             be found in self.kwargs
        """
        pk = self.kwargs.get('pk')

        qs = ThreediModel.objects.filter(
            threedi_model_repository_id=pk)

        self.search_str_raw = (
            self.request.GET.get('search') or self.search_str_raw
        )

        self.search_paceholder = (
            self.search_str_raw if self.search_str_raw
            else SEARCH_PLACEHOLDER
        )

        if self.search_str_raw:
            entry_query = inpy_search.get_query(
            self.search_fields, self.search_str_raw
            )
            qs = qs.filter(entry_query)
            logger.info(
            "[+] Found {0:d} entries for search {1}".format(
                len(qs), self.search_str_raw)
            )

        return qs

回溯

NoReverseMatch at /models/models/9999/
Reverse for 'revisions' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'models\\/revisions/(?P<pk>\\d+)/$']
Request Method: GET
Request URL:    http://localhost:9010/models/models/9999/
Django Version: 1.6.5
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'revisions' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'models\\/revisions/(?P<pk>\\d+)/$']
Exception Location: /home/vagrant/.buildout/eggs/Django-1.6.5-py2.7.egg/django/core/urlresolvers.py in _reverse_with_prefix, line 452
Python Executable:  /usr/bin/python
Python Version: 2.7.3

0 个答案:

没有答案