Login

Modelaware json serializer

Author:
fivethreeo
Posted:
March 18, 2007
Language:
Python
Version:
Pre .96
Tags:
json serialization
Score:
1 (after 1 ratings)

A serializer that handles dicts with querysets and model instances, nice to use if you have a paginator context.

paginate_by = 8

paginator = ObjectPaginator(queryset, paginate_by)
page = request.GET.get('page', 1)
try:
    page = int(page)
    object_list = paginator.get_page(page - 1)
except (InvalidPage, ValueError):
    if page == 1 and allow_empty:
        object_list = []
    else:
        raise Http404

result = {
    'object_list' : object_list,
    'is_paginated': paginator.pages > 1,
    'results_per_page': paginate_by,
    'has_next': paginator.has_next_page(page - 1),
    'has_previous': paginator.has_previous_page(page - 1),
    'page': page,
    'next': page + 1,
    'previous': page - 1,
    'pages': paginator.pages,
    'hits' : paginator.hits,

    }

serialize(result, ensure_ascii=False)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.core.serializers.json import DateTimeAwareJSONEncoder
from django.core import serializers
from django.db.models.query import QuerySet
from django.db.models import Model
from django.utils import simplejson

class ModelAwareJSONEncoder(DateTimeAwareJSONEncoder):
    def default(self, o):
        if isinstance(o, QuerySet):
            return serializers.serialize('python', o)
        if isinstance(o, Model):
            return serializers.serialize('python', [o])[0]
        else:
            return super(ModelAwareJSONEncoder, self).default(o)

def serialize(object, **options):
    return simplejson.dumps(object, cls=ModelAwareJSONEncoder, **options)

More like this

  1. Filter to adjust forloop.counter across pages in a paginated view by egmanoj 6 years, 3 months ago
  2. Pagination/Filtering Alphabetically by zain 6 years, 3 months ago
  3. Updated: GeoJSON Serializer for GeoDjango (gis) by danielsokolowski 3 years, 7 months ago
  4. JsonResponse by zakj 8 years, 3 months ago
  5. GeoJSON Serializer for GeoDjango (gis) by danielsokolowski 4 years, 1 month ago

Comments

Please login first before commenting.