开发者

What is the recommended way to serialize django data to json to work with jqgrid?

I've been spending my evening fighting with getting jsonReader: set up correctly in jqgrid to match the JSON output of django's serializer capabilities. I have since gotten sick of trying and decided I should just make a view to give the output jqgrid wants json to be in by default. My plan is to write a view that forms a string that looks like jqgrid wants it. This seems a bit ugly to me (ie lots of manual formatting of JSON), but I think this is probably the most expandable route for the future should I choose to use more functionality of jqgrid. What is the recommended way of getting custom formatted JSON 开发者_JS百科out of Django? What is the recommended Django way of accomplishing what I will accomplish by creating a view like the below example?

def serializedData(request):
    querySet = Model.objects.filter(date=None).order_by('id')
    data = '{'
    for row in querySet:
        # go through each item and make a pretty json row and add it to data
    data += '}'
    return HttpResponse(data)


This will do:

from django.utils import simplejson
return HttpResponse(simplejson.dumps(data), mimetype="application/json")


You should probably check out some of the serialization/API frameworks available out there :

  • django-piston, which I don't like so much since the serialization is not so flexible in my opinion.
  • SpitEat, which is built for allowing very flexible serialization, however the doc is completely outdated ... I don't find the time to fix it... but you can probably find your way by reading the tests, and the source code (which is completely documented and doc is up-to-date)
  • more packages there


I ended up creating a django template that matched the json format I wanted. This turned out to be a couple of lines so I can't imagine making it any simpler, especially when the names have to be manually assigned anyway.

example..something similar to this:

[{% for herp in derps %}
    { "id":"{{ herp.id }}___", "value":"{{ herp.value }}"}{% if not forloop.last %},{% endif %}
{% endfor %}]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜