这里主要是讲序列化单表的几种方法
先看下models中设计的表结构
from django.db import models # Create your models here. class Book(models.Model): id = models.AutoField(primary_key=True) book_name = models.CharField(max_length=64,null=False,blank=False,verbose_name="书籍名称") book_price = models.DecimalField(max_digits=5,decimal_places=2,null=False,blank=False,verbose_name="书籍价格") book_publish = models.ForeignKey(to="Publish",to_field="id",verbose_name="书籍出版社") book_auther = models.ManyToManyField(to="Auther",verbose_name="书籍作者") class Meta: verbose_name = "书籍表" verbose_name_plural = verbose_name def __str__(self): return self.book_name class Publish(models.Model): id = models.AutoField(primary_key=True) publish_name = models.CharField(max_length=64,null=False,blank=False) class Meta: verbose_name = "出版社表" verbose_name_plural = verbose_name def __str__(self): return self.publish_name class Auther(models.Model): id = models.AutoField(primary_key=True) auther_name = models.CharField(max_length=64,null=False,blank=False) def __str__(self): return self.auther_name class Meta: verbose_name = "作者表" verbose_name_plural = verbose_name
我们只对出版社表进行序列化,因为在我们这里的事例中,出版社表所有的字段都是单表字段,处理起来比较简单,后面我们就会介绍一对多和多对多字段的表该如何序列化
我们这里使用cbv的方式来测试
from django import views
下面先介绍三种序列化的方式
import json class test_cbv(views.View): def get(self,request,*args,**kwargs): # 一、序列化 publish_list = models.Publish.objects.all() publish_obj = models.Publish.objects.all().first() # 方式1 # ser1 = publish_list.values("id","publish_name") # ret1 = json.dumps(list(ser1)) # return HttpResponse(ret1) # 2、方式二 # from django.forms.models import model_to_dict # model_to_dict 把一个model对象转换为字典的方法 # ret2 = [] # for obj in publish_list: # temp.append(model_to_dict(obj)) # return HttpResponse(json.dumps(ret2)) # 3、方式3 # from django.core import serializers # serializers ---django的序列化组件 # ret3 = serializers.serialize(format="json",queryset=publish_list) # 指明格式为json,传递一个queryset对象进去就可以了 # return HttpResponse(ret3)
最后我们看下restframework序列化的方式,可以序列化一个queryset对象,也可以序列化一个model对象
首先需要通过pip安装restframworkork
pip install djangorestframework
然后按照下面的格式写一个类
# 为queryset或者model对象做序列化的类 from rest_framework import serializers class pub_serializers(serializers.Serializer): publish_name = serializers.CharField()
指明对表中哪些字段做处理,和django的froms组件很像
# 4、方式4 # ps_queryset = pub_serializers(publish_list,many=True) # return HttpResponse(ps_queryset.data) ps_model = pub_serializers(publish_obj) print(ps_model.data) return HttpResponse(ps_model.data)
至此,单表的序列化我们介绍完了!