Dealing with generator objects in the Paginator class.

Dear all,

I would like to know if you would consider the following change in the __ini__ method of the Paginator class (django.core.paginator.Paginator):

class Paginator:
    ...
    def  __init__(self, *args, **kwargs):
        self.object_list = list(object_list)  # insted of self.object_list = object_list

The reasoning behind this suggestion is that I would like to pass a generator for generating a sitemap. But the I do that I get the following a TypeError Exception.

The code that is generating this Exception is the following:

@cache
def get_active_tools():
    for tool in TOOLS:
        if tool.index_listing:
            yield tool


class ToolsSitemap(Sitemap):
    priority = 0.7
    changefreq = "never"

    def items(self):
        return get_active_tools()

    def location(self, item):
        return item.url

I can fix that by doing the following, but I would like not to do that.

@cache
def get_active_tools():
    tools = []
    for tool in TOOLS:
        if tool.index_listing:
            tools.append(tool)
    return tools

Thank you for your attention.

In the general case, this is going to be a very bad idea.

The problem with this is that it would force the execution of what might be a very large queryset, when only a small number of rows are needed.

If this is something that you’re going to find useful, then I would suggest you subclass Paginator and override the __init__ method. Or, use your workaround as described.

1 Like

Your code can be greatly shortened with a list comprehension:

@cache
def get_active_tools():
    return [tool for tool in TOOLS if tool.index_listing]

See Trey Hunner’s post for an explanation.

1 Like