views:

93

answers:

4

I've found myself unsatisfied with Django's ability to render JSON data. If I use built in serializes then database foreign key relationships are not included in the data (only the keys). Also, it seems to be impossible to include custom data in the json feed that isn't part of the model being serialized.

As a test I implemented a template that rendered some JSON for the resultset of a particular model. I was able to include/exclude whatever parts of the model I wanted and was able to include custom data as well.

The test seemed to work well and wasn't slower than the recommended serialization methods.

Are there any pitfalls to this using this method of serialization?

+1  A: 

While it's hard to say definitively whether this method has any pitfalls, it's the method we use in production as you control everything that is serialized, even if the underlying model is changed. We've been running a high traffic application in for almost two years using this method.

Hope this helps.

godswearhats
How did you address the 'escaping' problem mentioned above?
theycallmemorty
We've not run into any issues with escaping. I know that we have special characters in our data all the time, which must mean that whatever is consuming the data de-escapes them.
godswearhats
A: 

One problem might be escaping metacharacters like ". Django's template system automatically escapes dangerous characters, but it's set up to do that for HTML. You should look up exactly what the template escaping does, and compare that to what's dangerous in JSON. Otherwise, you could cause XSS problems.

You could think about constructing a data structure of dicts and lists, and then running a JSON serializer on that, rather than directly on your database model.

rescdsk
A: 

We use this method to get custom JSON format consumed by datatables.net It was the easiest method we find to accomplish this task and it looks very fine with no problems so far.

You can find details here: http://datatables.net/development/server-side/django

Lukasz Dziedzia
+1  A: 

I don't understand why you see the choice as being either 'use Django serializers' or 'write JSON in templates'. The middle way, which to my mind is much more robust and fits your use case well, is to build up your data as Python lists/dictionaries and then simply use simplejson.dumps() to convert it to a JSON string.

Daniel Roseman