序列化组件的使用及接口设计
通过序列化的组件进行接口设计
--GET : 127.0.0.1:8000/books/ # 获取所有数据,返回值: [{}, {}]
GET : 127.0.0.1:8000/books/{id} # 获取一条数据,返回值:{}
POST : 127.0.0.1:8000/books/ # 新增一条数据,返回值:{}
PUT : 127.0.0.1:8000/books/{id} # 修改数据,返回值:{}
DELETE: 127.0.0.1:8000/books/{id} # 删除数据,返回空
执行流程:
modes.py
from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) age = models.IntegerField() def __str__(self): return self.name class Publish(models.Model): nid = models.AutoField(primary_key=True) name = models.CharField(max_length=32) city = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField(max_length=32) price = models.DecimalField(max_digits=5, decimal_places=2) # 外键字段 publish = models.ForeignKey(to="Publish", related_name="book", related_query_name="book_query", on_delete=models.CASCADE) # 多对多字段 authors = models.ManyToManyField(to="Author")
1.导入模块: from rest_framwork import serializes
2.创建一个序列化的类 class BookSerializer(serializers.Serializer):
class BookSerializer(serializers.Serializer): # nid = serializers.CharField(max_length=32) title = serializers.CharField(max_length=128) price = serializers.DecimalField(max_digits=5, decimal_places=2) # 外键字段, 显示__str__方法的返回值 publish = serializers.CharField(max_length=32, source="publish.city") # authors = serializers.CharField(max_length=32) # book_obj.authors.all() # 多对多字段需要自己手动获取数据,SerializerMethodField() authors_list = serializers.SerializerMethodField() def get_authors_list(self, book_obj): author_list = list() for author in book_obj.authors.all(): author_list.append(author.name) return author_list def create(self, book_obj): return book_obj
视图:
1.导入模序列化类的模块,和APIView模块
from.app_serializers import BookSerializer
from rest_framework.views import APIView
2.创建类(携带参数和不携带参数)
class BookView(APIView)
def get(self,request);
#获取request
origin_data=Book.objects.all()
#开始序列化
serialized_data=BookSerializer(origin_data,many=True)
return Response(serialized_data.data)
def post(self,request):
verified_data=BookSerializer(data=request.data)
if verified.is_valid():
book=verified_data.save()
authors=Author.objects.filter(nid__in=request.data['authors'])
book.authors.add(*authors)
return Response(verifiled_data.data)
else:
return Response(verifiled_data.errors)
class BookFilterView(APIView):
def get(self,request,nid)
book_obj=Book.objects.get(pk=nid)
serialized_data=BookSerialzer(book_obj,many=False)
return Response(serialized_data.data)
def put(self,request,nid):
book_obj=Book.objects.get(pk=nid)
verfiled_data=BookSerializer(data=request.data,instabce=book_oobj)
if verfiles_data.is_valid():
verfiled_data.save()
return Response(verfiled_data.data)
else:
retuen Response(vefriled_data.errors)
def delete(self,request,nid):
book_obj=Book.objects.get(pk=nid).delete()
return Response()