5π
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
PER_PAGE = 20
def list(request):
"""
Return a paginated JSON object.
"""
paginator = Paginator(tasks.objects.all(), PER_PAGE)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
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
π€Mikesname
5π
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))
π€mmbrian
- Django abstract parent model save overriding
- Two Django projects running simultaneously and mod_wsgi acting werid
- Object Ownership in Django
2π
The django Restframework
offers a special PaginationSerializer
which does just what you want I guess.
π€codingjoe
- Authorization in social networking website
- Differentiating between different post requests on the same page in Django views.py
- Creating many related objects like INSERT β¦ SELECT in SQL
- ModuleNotFoundError: No module named 'phonenumbers'
Source:stackexchange.com