我需要在自定义json
中插入两个json序列化模型我尝试使用json.dumps,但vars(objects1,objects2)转换为字符串
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")
答案 0 :(得分:1)
一种相当简单的方法是在转储它们之前load
序列化查询集:
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)})
这肯定会有转储+加载+转储操作的开销。
另一种选择是使用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})