Example of a method by django to convert model to a dictionary

  • 2020-12-18 01:51:45
  • OfStack

In the normal development process, it is inevitable to encounter the need to turn model into a dictionary, especially in the current fashion of front and rear end separation architecture, Json format has almost become the standard for data exchange between front and rear ends, and this kind of model to dict is even more required. This paper introduces the method used in daily use for reference


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': ' Fall in love with local ',
 'proname': ' A literary intelligentsia ',
 'prostatus': '',
 'prosummary': '',
 'protype': ' Whether to play ',
 'regstudy': ' is ',
 'reportdate': None,
 'reportnum': '',
 'reportversion': '',
 'researchdesign': '',
 'researchtype': '',
 'responsible': '',
 'studytype': ' Equipment class ',
 'telephonenum': None,
 'totalcases': None,
 'treatmenttype': None,
 'unitnum': None}

Related articles: