django中将models以json形式返回

views里一开始这么写的

from django.core import serializers

         data = serializers.serialize("json", Host_info.objects.all())
         data = Host_info.objects.all().values()
         print data
         data = simplejson.dumps(data)
         return HttpResponse(data, mimetype="application/json")

但是发现界面居然不识别,不知到什么原因。

只好改成如下方式转换了

from datetime import date, datetime

def discoverhosts(request):
    if request.method == "GET":
        queryset =  Host_info.objects.all()
        data = []
        for row in queryset:
            data.append({'mac':row.mac,'ip':row.ip,'status':row.status,'description':row.description})
        json_data = simplejson.dumps(data,default=__default)
        return HttpResponse(json_data, mimetype="application/json")
def __default(obj):
	if isinstance(obj, datetime):
		return obj.strftime('%Y-%m-%dT%H:%M:%S')
	elif isinstance(obj, date):
		return obj.strftime('%Y-%m-%d')
	else:
		raise TypeError('%r is not JSON serializable' % obj)


你可能感兴趣的:(django)