Django StopIteration问题

时间:2019-04-03 09:36:45

标签: python django list stopiteration

根据我的问题,我希望得到您的帮助:StopIteration

Principe:

我有一个函数,它获取一个ID列表和一个特定ID作为参数。此ID列表与具有分页的数组相对应。

在此数组中创建新对象时,将调用此函数。创建对象后,我将重定向到数组中的好页面。

我的功能:

def get_pagination(my_list_of_objects, pk):
    # if object doesn't exist, add id to list of objects
    if pk not in my_list_of_objects:
        my_list_of_objects.append(pk)

    # Get the list of objects code splitted by PAGE_LIMIT sorted by code (default)
    my_list_of_objects_code = MyModel.objects.values_list('code', flat=True).filter(id__in=my_list_of_objects)
    pagination = [my_list_of_objects_code[x:x + settings.PAGE_LIMIT] for x in range(0, len(my_list_of_objects_code), settings.PAGE_LIMIT)]

    # Get first and last page number
    first_page = 1
    last_page = len(pagination)

    # Get sublist index (e.g page number for specific id)
    page_number = (next(index for index, value in enumerate(pagination) if pk in value)) + 1
    return pagination, first_page, last_page, page_number

通过这种方式:

my_list_of_objects:对象ID列表

my_list_of_objects_code:按代码排序的对象列表

分页::将列表分成包含n个元素的子列表。 n对应于在设置中设置的分页。

第一页:首页编号(例如默认为1)

最后一页:最后一页编号(例如子列表数量)

页码:获取创建对象所在的页码

示例:

settings.PAGE_LIMIT = 5
pk: 119
my_list_of_objects_code: <QuerySet ['a', 'aa', 'aaa', 'aaaa', 'aasza', 'abaaa', 'aqqq', 'asz', 'asza', 'awq', 'azazaza', 'azeaze', 'bgre', 'cdezf', 'da',...]>
pagination: [['a', 'aa', 'aaa', 'aaaa', 'aasza'], ['abaaa', 'aqqq', 'asz', 'asza', 'awq'], ['azazaza', 'azeaze', 'bgre', 'cdezf', 'da']...]
first_page: 1
last_page: 18

问题:

调用函数时,出现此问题:

  

异常类型:StopIteration

     

文件“ /home/Bureau/Projets/APP/my_app/src/my_app/views/main.py”在   get_pagination     1830. page_number =(next(索引索引,如果pk值,则为枚举(分页)))+ 1

我不明白如何解决此问题。如果我需要try/except,该怎么办?

谢谢

编辑:

def get_pagination(my_list_of_objects, pk):
    # if object doesn't exist, add id to list of objects
    if pk not in my_list_of_objects:
        my_list_of_objects.append(pk)

    # Get the list of objects code splitted by PAGE_LIMIT sorted by code (default)
    my_list_of_objects_code = MyModel.objects.values_list('code', flat=True).filter(id__in=my_list_of_objects)
    pagination = [my_list_of_objects_code[x:x + settings.PAGE_LIMIT] for x in range(0, len(my_list_of_objects_code), settings.PAGE_LIMIT)]

    # Get first and last page number
    first_page = 1
    last_page = len(pagination)

    try:
        page_number = (next(index for index, value in enumerate(pagination) if MyModel.objects.get(pk=pk).code in value)) +1

    except StopIteration:
        page_number = 1
    return pagination, first_page, last_page, page_number

0 个答案:

没有答案