由previous_page_number()方法引发的意外异常 - Django Paginator

时间:2017-04-06 10:54:17

标签: django paginator

>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)
>>> p.count
4
>>> p.num_pages
2
>>> page1 = p.page(1)
>>>
>>> page1.previous_page_number()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Users\Rick\ws2\env\lib\site-packages\django\core\paginator.py", line 136
, in previous_page_number
    return self.paginator.validate_number(self.number - 1)
  File "C:\Users\Rick\ws2\env\lib\site-packages\django\core\paginator.py", line 38,
 in validate_number
    raise EmptyPage('That page number is less than 1')
django.core.paginator.EmptyPage: That page number is less than 1
>>>

根据previous_page_number()文档。

  

Page.previous_page_number()

     

返回上一页码。如果上一页不存在,则引发InvalidPage

正如文档所说,我期待previous_page_number()提出InvalidPage例外。为什么它会返回EmptyPage例外?

我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

根据1.10中的paginator来源( django.core.paginator.py ):

def validate_number(self, number):
    """
    Validates the given 1-based page number.
    """
    try:
        number = int(number)
    except (TypeError, ValueError):
        raise PageNotAnInteger('That page number is not an integer')
    if number < 1:
        raise EmptyPage('That page number is less than 1')
    if number > self.num_pages:
        if number == 1 and self.allow_empty_first_page:
            pass
        else:
            raise EmptyPage('That page contains no results')
    return number

根据您的条件:数字将小于1,因此会提高

EmptyPage('That page number is less than 1')

但根据Django文档,它应该已经提升了基本异常 InvalidPage

在编写 previous_page_number()

的文档时,这可能是一个拼写错误

但是根据InvalidPage解释, EmptyPage 异常仅限于此。所以它只是InvalidPage的详细/派生异常。