jquery – 在Django中序列化分页对象的任何方法?

前端之家收集整理的这篇文章主要介绍了jquery – 在Django中序列化分页对象的任何方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Django jQuery与jQuery.我可以序列化分页对象的对象列表,但我想序列化整个对象以获取更多数据(页码,总页数……).
如何序列化整个分页对象?

谢谢

JavaScript

function getRestaurants(query) {

        $.post("/getRestaurant/",query,function(data) {
                /* do stuff with data */
             },"json" );
}

views.py

def getRestaurant(request):

    results = Restaurant.objects.all()
    paginator = Paginator(restaurants,5)

    # Make sure page request is an int. If not,deliver first page.
    try:
        page = int(request.POST.get('page','1'))
    except ValueError:
        page = 1

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

    data=serializers.serialize("json",results.object_list) #I'd like to serialize the whole results object

    return HttpResponse(data)

解决方法

我只需要为此制作一个hacky解决方案,所以我会将其作为答案发布 – 欢迎任何改进:
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',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

猜你在找的jQuery相关文章