明瞳 2020-02-17
定义序列化器(本质就是一个类),一般包括模型类的字段,有自己的字段类型规则。实现了序列化器后,就可以创建序列化对象以及查询集进行序列化操作,通过序列化对象.data来获取数据(不用自己构造字典,再返回Json数据)
INSTALLED_APPS = [ ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘apps.apps.AppsConfig‘, ‘app01‘, ‘rest_framework‘, #把drf组件注册进去 ]
项目主目录/settings.py
from django.db import models # Create your models here. class Book(models.Model): nid = models.IntegerField(primary_key=True) title = models.CharField(max_length=32) #第三张表 author = models.ManyToManyField(to=‘Author‘) class Publish(models.Model): nid = models.IntegerField(primary_key=True) name = models.CharField(max_length=32) address = models.CharField(max_length=32) email = models.EmailField(max_length=128) class Author(models.Model): nid = models.IntegerField(primary_key=True) name =models.CharField(max_length=32) age = models.IntegerField()
app01/models.py
from django.shortcuts import render from django.db import models from .models import Book from .models import Publish from .models import Author # Create your views here. from apps.models import Course from django.core.serializers import serialize from rest_framework.views import APIView from rest_framework import serializers from rest_framework.response import Response #创建一个序列化类 class BookSerizlizer(serializers.Serializer): nid = serializers.CharField(max_length=10) title = serializers.CharField(max_length=32) #把书本关联的作者添加到数据池中 author = serializers.SerializerMethodField() #创建一个方法必须 :get_字段名,并传入一个对象。 def get_author(self,book_obj): author_list = list() for a in book_obj.author.all(): author_list.append({‘name‘:a.name,‘age‘:str(a.age)}) return author_list class Courses(APIView): def get(self,request): old_data = Book.objects.all() #开始序列化json数据 new_data = BookSerizlizer(old_data,many=True) print(Response) #将序列化之后的数据,响应给客户端 return Response(new_data.data) def post(self,request): pass