Django学习笔记(13)model_to_dict 的使用

用于将model实例转换为dict

  

1 from django.forms.models import model_to_dict
2 di = model_to_dict(order, exclude=['create_time', 'update_time'])

源码函数声明:def model_to_dict(instance, fields=None, exclude=None):
其中参数instance是对象实例,fields是指定需要哪些字段,exclude是指定排除哪些字段,exclude比fields优先级高。

model_to_dict的一个应用

 1 def case_set_new(req):
 2     if req.method == 'GET':
 3         case_sets = models.CaseSet.objects.filter(is_delete=False)
 4         data = []
 5         for c in case_sets:
 6             d = model_to_dict(c)
 7             data.append(d)
 8         response = {'code': 0, 'msg': '添加成功', 'data': data}
 9         return JsonResponse(response, json_dumps_params={'ensure_ascii': False})  # 汉字不转义
10     elif req.method == 'POST':
11         name = req.POST.get('name')
12         desc = req.POST.get('desc')
13         if name.strip() and desc.strip():
14             models.CaseSet.objects.create(name=name, desc=desc)
15             data = {'code': 0, 'msg': '添加成功'}
16         else:
17             data = {'code': -1, 'msg': '参数错误'}
18         return JsonResponse(data)  # 通过JsonResponse类返回json字符串
19     elif req.method == 'PUT':
20         pass
21     elif req.method == 'DELETE':
22         pass

猜你喜欢

转载自www.cnblogs.com/bugoobird/p/13366261.html
今日推荐