model对象转dict

model内容示例:

class Student(models.Model):
       name = models.CharField(verbose_name=u'姓名', max_length=200)
       sex = models.CharField(verbose_name=u'性别', max_length=200)
       heigh = models.IntegerField(verbose_name=u"身高")
       age = models.IntegerField(verbose_name=u"n年龄")

       class Meta:
            verbose_name = u"学生信息表"
            db_table = 'student'

方法一:

    笨方法:
         data = modes.Student.objects.get(id)
         dict = {
              "id": data.id,
              "name": data.name,
              "sex" : data.sex
              } 

方法二:

    通过第三方库:
      from playhouse.shortcuts import model_to_dict
      
      data = modes.Student.objects.filter(id)
      for item in data:
            dict = model_to_dict(item)

你可能感兴趣的:(model对象转dict)