Question

I need insert two json serialized models inside custom json

I tried using json.dumps but the vars (objects1, objects2) converts in string

objects1 = Objects1.objects.all()
objects2 = Objects2.objects.all()

json_objects1 = serializers.serialize("json", objects1)
json_objects2 = serializers.serialize("json", objects2)

data = json.dumps("first_objects": json_objects1, "second_objects":json_objects2)

return HttpResponse(data, content_type="application/json; charset=utf-8")
Was it helpful?

Solution

One, rather straightforward approach, would be to load serialized querysets before dumping them:

json_objects1 = serializers.serialize("json", objects1)
json_objects2 = serializers.serialize("json", objects2)

data = json.dumps({"first_objects": json.loads(json_objects1), 
                   "second_objects": json.loads(json_objects2)})

This certainly has an overhead of dumping+loading+dumping operation.

Another option would be to use model_to_dict():

from django.forms import model_to_dict

objects1 = [model_to_dict(item) for item in objects1]
objects2 = [model_to_dict(item) for item in objects2]

data = json.dumps({"first_objects": objects1, 
                   "second_objects": objects2})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top