views:

49

answers:

1

It's easy to serialize models in an iterable:

def _toJSON(models):
    return serializers.serialize("json", models, ensure_ascii=False)

What about when I have something more complicated:

[
(Model_A_1, [Model_B_1, Model_B_2, Model_B_3]),
(Model_A_2, [Model_B_3, Model_B_4, Model_B_5, Model_B_59]),
(Model_A_3, [Model_B_6, Model_B_7]),
]

I tried serializing each model as it was added to the structure, then serializing the whole thing with simplejson.dumps, but that causes the JSON defining each model to be escaped.

Is there a better way to do this?

A: 

I am not sure if my proposal is a 'better way' but it worked for me for some cases when custom json format was required.

The idea is to create some django template that will create json in a format you need (probably couple of for loops). This template + conext with your models structure should give json you are looking for.

Of course there are some drawbacks here that need to be mentioned. It would be a pain to deserialize such json in python, it might not be so fast as other solutions and probably others. But in case if this is not a problem for you, I think this solution is quite handy and can help you move forward with your project.

Lukasz Dziedzia