json_filters.py 542 Bytes
Newer Older
Okhin's avatar
Okhin committed
1
2
3
4
5
6
7
8
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()

Okhin's avatar
Okhin committed
9
@register.filter(name='jsonify')
Okhin's avatar
Okhin committed
10
11
12
def jsonify(object):
    if isinstance(object, QuerySet):
        return serialize('json', object)
13
14
    elif object == []:
        return json.dumps(object)
Okhin's avatar
Okhin committed
15
16
17
18
    elif isinstance(object[0], SearchResult):
        return serialize('json', [x.object for x in object])
    else:
        return json.dumps(object)