Django: Serializing models in a nested data structure?

Easy to serialize models in an iterable:

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

      

How about when I have something more complex:

[
(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 struct and then serializing the whole thing with simplejson.dumps

, but this forces JSON to define each model to be escaped.

Is there a better way to do this?

+2


a source to share


1 answer


I'm not sure if my suggestion is the "best way", but it worked for me in some cases where custom JSON format is required.

The idea is to create some django template that will generate the json in the format you want (maybe a couple of loops for loops). This conext template with your model structure should give the json you are looking for.



Of course, there are some disadvantages here that need to be mentioned. It would be a pain to deserialize such JSON in Python, it might not be as fast as other solutions and possibly others. But in case this is not a problem for you, I think this solution is very convenient and can help you move forward with your project.

0


a source







All Articles