json_filters.py 489 Bytes
Newer Older
Okhin's avatar
Okhin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.template import Library
from haystack.models import SearchResult
import json

register = Library()

def jsonify(object):
    if isinstance(object, QuerySet):
        return serialize('json', object)
    elif isinstance(object[0], SearchResult):
        return serialize('json', [x.object for x in object])
    else:
        return json.dumps(object)

register.filter('jsonify', jsonify)