Django查询表数据转换成JSON格式
- 直接利用python提供的json包,在django model的定义中增加一个方法toJSON,利用django model 能访问 _meta.fields 得到相关属性而得到,例子如下:
model层:
class StudentInfo(models.Model):
stu_id = models.CharField(primary_key=True, max_length=20)
stu_name = models.CharField(max_length=20)
stu_password = models.CharField(max_length=20)
def __unicode__(self):
return '%s' % self.stu_name
def toJSON(self):
import json
return json.dumps(dict([(attr, getattr(self, attr)) for attr in [f.name for f in self._meta.fields]]))
查询语句:
from .models import StudentInfo
def Search(request):
students = StudentInfo.objects.get(stu_name='zhangsan')
return HttpResponse(students.toJSON())