[Solved]-Any way to serialize a pagination object in Django?


I’ve just had to make a hacky solution for this so I’ll post it as an answer – any improvements welcome:

from django.core import serializers
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse
from django.utils import simplejson  
from types import MethodType 

from mysite.tasks.models import Task


def list(request):
    Return a paginated JSON object.

    paginator = Paginator(tasks.objects.all(), PER_PAGE) 
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
        pagetasks = paginator.page(page)
    except (EmptyPage, InvalidPage):
        pagetasks = paginator.page(paginator.num_pages)

    # Dump the Page attributes we want to a dictionary
    serializedpage = {}
    wanted = ("end_index", "has_next", "has_other_pages", "has_previous",
            "next_page_number", "number", "start_index", "previous_page_number")
    for attr in wanted:
        v = getattr(tasks, attr)
        if isinstance(v, MethodType):
            serializedpage[attr] = v()
        elif isinstance(v, (str, int)):
            serializedpage[attr] = v

    # Serialise the queryset to plain Python objects 
    # and add them to the serialized page dictionary
    pythonserializer = serializers.get_serializer("python")()
    serializedpage["object_list"] = pythonserializer.serialize(pagetasks.object_list, 
            fields=('task_id', 'task_data')) 

    # Dump it as JSON using the Django encoder
    response = HttpResponse(mimetype="application/json")
    simplejson.dump(serializedpage, response, cls=DjangoJSONEncoder)
    return response                               


my suggestion is to discard the paginator object & slice the queryset yourself. this way you could easily serialize the output.

as an example, here’s how you might wanna do that if you wanna serialize a list of comments into json format:

comment_list = ArticleComment.objects.filter(article__id=int(_id), is_public=True).values('created', 'tag', 'content', 'author').order_by('-created')   
    start = (page_num - 1) * COMMENTS_PER_PAGE
    end = page_num * COMMENTS_PER_PAGE
    return HttpResponse(json.dumps(list(comment_list[start:end]), cls=DjangoJSONEncoder))


The django Restframework offers a special PaginationSerializer which does just what you want I guess.


Leave a comment