一、先建好表格
models.py
class Book(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
publish_date = models.DateField()
publish = models.ForeignKey(to='Publish', to_field='nid', on_delete=models.CASCADE)
authors = models.ManyToManyField(to='Author')
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.IntegerField()
author_detail = models.OneToOneField(to='AuthorDatail', to_field='nid', unique=True, on_delete=models.CASCADE)
class AuthorDatail(models.Model):
nid = models.AutoField(primary_key=True)
telephone = models.BigIntegerField()
birthday = models.DateField()
addr = models.CharField(max_length=64)
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()
二、写一个序列化类继承ModelSerializer
新建myser.py文件
from rest_framework import serializers
from app01 import models
class BookSerializers(serializers.ModelSerializer):
class Meta:
model = models.Book
fields = '__all__'
三、在视图函数使用序列化的类
views.py:
from rest_framework.views import APIView
from app01 import models
from app01.myser import BookSerializers
from rest_framework.response import Response
class Books(APIView):
def get(self, request, *args, **kwargs):
response = {'code': 100, 'msg': '查询成功'}
ret = models.Book.objects.all()
book_ser = BookSerializers(instance=ret, many=True)
response['data'] = book_ser.data
return Response(response)
def post(self, request, *args, **kwargs):
response = {'code': 100, 'msg': '新增成功'}
book_ser = BookSerializers(data=request.data)
if book_ser.is_valid():
book_ser.save()
else:
response['code'] = 101
response['msg'] = book_ser.errors # 错误信息被response序列化出来返回前端
return Response(response)
class BookDetail(APIView):
def get(self, request, id, **kwargs): # id是有名分组传过来的id
response = {'code': 100, 'msg': '查询成功'}
ret = models.Book.objects.filter(pk=id).first()
book_ser = BookSerializers(instance=ret, many=False)
response['data'] = book_ser.data
return Response(response)
def put(self, request, id, **kwargs):
response = {'code': 100, 'msg': '修改成功'}
ret = models.Book.objects.filter(pk=id).first()
book_ser = BookSerializers(instance=ret, data=request.data) # 修改需要传两个参数
if book_ser.is_valid():
book_ser.save() # 校验通过,如果不是空,调update方法, 如果是空,调create方法
# 原因是ModelSerializer 重写了这两个方法
else:
response['code'] = 101
response['msg'] = book_ser.errors
return Response(response)
def delete(self, request, id, **kwargs):
response = {'code': 100, 'msg': '删除成功'}
models.Book.objects.filter(pk=id).delete()
return Response(response)
urls.py
url(r'^books/$', views.Books.as_view()),
url(r'^books/(?P<id>d+)$', views.BookDetail.as_view()),
演示:
新增数据
修改数据