views.py
def json(request):
defaultnumber = []
phoneinfo = PhoneInfo.objects.filter(user = user_id)
for phone in phoneinfo:
phone_no = {'id':some.id,
'name1':phone.name1,
'number1':phone.number1,
'name2':phone.name2,
'number2':phone.number2,
} }
defaultnumber.append(phone_no)
result = { 'phone':defaultnumber}
return HttpResponse(json.dumps(result), mimetype="application/json")
我需要将数据发送到json格式。
答案 0 :(得分:1)
改为使用model_to_dict
:
from django.forms.models import model_to_dict
def json_view(request):
phoneinfo = PhoneInfo.objects.filter(user = user_id)
phones = [model_to_dict(phone) for phone in phoneinfo]
result = {'phoneinfo': phones}
return HttpResponse(json.dumps(result), mimetype="application/json")
并且,请勿调用查看json
- 您正在覆盖json
模块名称。
并且,user_id
变量来自哪里不清楚。