django 将model转换为字典的方法示例

yipeiwu_com5年前Python基础

平常的开发过程中不免遇到需要把model转成字典的需求,尤其是现在流行前后端分离架构,Json格式几乎成了前后端之间数据交换的标准,这种model转dict的需求就更多了,本文介绍日常使用的方法以供参考

from django.forms.models import model_to_dict
from projects.models import ProjectInformation


site = ProjectInformation.objects.get(id=6)
dict = model_to_dict(site)

dict

{'CRFmethod': '',
 'EDCprovider': '',
 'acceptancenum': '',
 'add_time': datetime.datetime(2017, 4, 20, 8, 4, 42, 751202, tzinfo=<UTC>),
 'begindate': None,
 'clinicalassis': '',
 'clinicalnum': '',
 'created_by': '',
 'created_date': None,
 'enddate': None,
 'ethicsreviewdate': None,
 'ethicsreviewpers': '',
 'ethicsreviewres': '',
 'ethicsreviewunit': '',
 'id': 6,
 'isimport': None,
 'leaderunit': None,
 'localcases': None,
 'medicalequipment': '',
 'mequipmenttype': '',
 'multicenter': '',
 'plannum': '',
 'proenname': '爱上地方',
 'proname': '打士大夫',
 'prostatus': '',
 'prosummary': '',
 'protype': '打是否',
 'regstudy': '是',
 'reportdate': None,
 'reportnum': '',
 'reportversion': '',
 'researchdesign': '',
 'researchtype': '',
 'responsible': '',
 'studytype': '器械类',
 'telephonenum': None,
 'totalcases': None,
 'treatmenttype': None,
 'unitnum': None}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

遗传算法python版

遗传算法python版

本文实例为大家分享了python遗传算法的具体代码,供大家参考,具体内容如下 1、基本概念 遗传算法(GA)是最早由美国Holland教授提出的一种基于自然界的“适者生存,优胜劣汰”基...

对python创建及引用动态变量名的示例讲解

实际上在python中用列表就可以实现动态变量名的管理,python中的列表中可以存储任何类型的元素: listA = [0,"str",B()] 上述列表分别存储了整数,字符串...

python 文件的基本操作 菜中菜功能的实例代码

python  文件的基本操作 菜中菜 文件操作 ​ open():打开 ​ file:文件的位置(路径) ​ mode:操作文件模式 &#...

python中 ? : 三元表达式的使用介绍

(1) variable = a if exper else b(2)variable = (exper and [b] or [c])[0](2) variable = exper a...

解决Django连接db遇到的问题

解决Django连接db遇到的问题

1、django.db.utils.ConnectionDoesNotExist: The connection default doesn't exist 解决:第一个连接的命名一定...