查看:
def some_view(request,number):
car=Car.objects.get(id=number)
person=Person.objects.get(name=car.owner)
car_json=serializers.serialize("json",[car])
car_json = car_json.strip("[]")
person_json=serializers.serialize("json",[person])
person_json = person_json.strip("[]")
return HttpResponse(car_json, mimetype="application/json")
我能够将单个json对象传递给模板。但是我如何传递car_json和person_json?
答案 0 :(得分:1)
你可以将它们组合成一个对象,然后发送它们,因为你只能发送一个dict作为响应:
e.g。
obj = {
'car': serializers.serialize('json', [Car.objects.get(id=number)]).strip("[]"),
'person': serializers.serialize('json', [Person.objects.get(name=car.owner)]).strip("[]")
}
obj_json = json.dumps(obj)
您还可以使用Car.objects.filter(id=number)
和Person.objects.filter(name=car.owner)
..只需稍加优化
答案 1 :(得分:0)
all_objects = list(Restaurant.objects.all()) + list(Place.objects.all())
data = serializers.serialize('json', all_objects)
更多:https://docs.djangoproject.com/en/dev/topics/serialization/