[Answer]-How to mix JSON-serialized Django models with flat JSON

1👍

My solution involved dropping the use of django.core.serializers and instead using django.forms.model_to_dict and django.core.serializers.json.DjangoJSONEncoder.

The resulting code looked like this:

for indicator in indicators:
    score_data = {}
    score_data["indicator"] = model_to_dict(indicator)
    score_data["score"] = evaluation.indicator_percent_score(indicator.id)
    score_data["score_descriptor"] = \
        model_to_dict(form.getDescriptorByPercent(score_data["score"]), 
            fields=("order", "value", "title"))

    scores.append(score_data)
scores = json.dumps(scores, cls=DjangoJSONEncoder)

The problem seemed to arise from the fact that I was essentially serializing the Django models twice. Once with the django.core.serializers function and once with the json.dumps function.

The solution solved this by converting the model to a dictionary first, throwing it in the dictionary with the other data and then serializing it once using the json.dumps using the DjangoJSONEncoder.

Hope this helps someone out because I couldn’t find my specific issue but was able to piece it together using other answer to other stackoverflow posts.

Leave a comment