FoamyGuy
FoamyGuy

Reputation: 46846

Django jsonify a single model object inside of a template

I have a jsonify templatetag:

from django.core.serializers import serialize
from django.db.models.query import QuerySet
from django.core.serializers.json import DjangoJSONEncoder
from django.utils import simplejson
from django.template import Library
from django.utils.safestring import mark_safe

register = Library()

def jsonify(object):
    if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
    return mark_safe(simplejson.dumps(object, cls=DjangoJSONEncoder))

register.filter('jsonify', jsonify)

This works fine when I want to jsonify an entire QuerySet. But I am having trouble being able to jsonify just a single item within a query set.

{% for t in ticket_set %}
    <tr class="clickableRow tip-top" onclick="rowClick('{{ t | jsonify }}');" >

{% endfor %}

when the template tag tries to jsonify a single item t rather than the whole set ticket_set I get an error:

<ProblemTicket: SMITH, JOHN - XXXXXXXXX; 2014-07-16 19:09:21.140000+00:00> is not JSON serializable

It looks like it is trying to jsonify the result that it gets back from calling __str__ on the model object which is defined like this:

def __str__(self):
        return "%s, %s - %s; %s" % (self.person.last_name, self.person.first_name, self.serial_number, self.date_time)

What do I need to do in order to get my jsonify method to work correctly on a single django model object rather than a set of them?

Upvotes: 2

Views: 2323

Answers (1)

janos
janos

Reputation: 124648

This will work, but the json will be an array:

def jsonify(object):
    if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
    return mark_safe(serialize('json', [object]))

This will remove the array wrapper, but it's ugly:

def jsonify(object):
    if isinstance(object, QuerySet):
        return mark_safe(serialize('json', object))
    return mark_safe(json.dumps(json.loads(serialize('json', [object])))[0])

It would be best to somehow get DjangoJSONEncoder to serialize the object properly but I don't know how...

Upvotes: 3

Related Questions