- Author:
- fivethreeo
- Posted:
- March 18, 2007
- Language:
- Python
- Version:
- Pre .96
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.