Django controller method to list the top characters, guilds, and killers I've been reading the Chapter 8 of this book.

Here's the view I'm currently coding. It list all characters/guilds according to the type of URL.


/ranking -&gt; List Top 50 Characters

/ranking/guild -&gt; List top guilds

/ranking/pvp -&gt; list top killers



def ranking(request, type):
    if type=='':
        queryset_list = Character.objects.annotate(num_resets=Count('resets')).order_by('-resets').select_related('account')[:50]
        paginator = Paginator(queryset_list, 10)

        page = request.GET.get('page')
        try:
            queryset = paginator.page(page)
        except PageNotAnInteger:
            queryset = paginator.page(1)
        except EmptyPage:
            queryset = paginator.page(paginator.num_pages)
            context = {'object_list' : queryset, 'states':STATES, 'class_type':CLASS_TYPE}
        template = 'ranking_character.html'
    elif type=='guild':
        queryset_list = Guild.objects.all()
        paginator = Paginator(queryset_list, 10)

        page = request.GET.get('page')
        try:
            queryset = paginator.page(page)
        except PageNotAnInteger:
            queryset = paginator.page(1)
        except EmptyPage:
            queryset = paginator.page(paginator.num_pages)

        context = {'object_list' : queryset}
        template = 'ranking_guild.html'

    elif type=='pvp':
        queryset_list = Character.objects.filter(pk_count__gt=0).annotate(total=Count('pk_count')).order_by('-pk_count')[:50]
        paginator = Paginator(queryset_list, 10)

        page = request.GET.get('page')
        try:
            queryset = paginator.page(page)
        except PageNotAnInteger:
            queryset = paginator.page(1)
        except EmptyPage:
            queryset = paginator.page(paginator.num_pages)
            context = {'object_list' : queryset, 'class_type':CLASS_TYPE}
        template = 'ranking_pvp.html'

    return render(request,template,context)


It's possible to make it more "generic"? How can I abstract this different queryset?
I think you can just make a function to get the queryset and re-use it:

def queryset_from_page():
    page = request.GET.get('page')
    try:
        return paginator.page(page)
    except PageNotAnInteger:
        return paginator.page(1)
    except EmptyPage:
        return paginator.page(paginator.num_pages)


Also why is context being defined at different indentation levels?

    except EmptyPage:
        queryset = paginator.page(paginator.num_pages)

    context = {'object_list' : queryset}


vs

    except EmptyPage:
        queryset = paginator.page(paginator.num_pages)

        context = {'object_list' : queryset, 'class_type':CLASS_TYPE}


In one case you define context everytime, other times only when a particular branch in the exception handling is taken: is this a bug?