一、总纲
1、一切皆资源,操作既请求
2、分析
一个类(无参数)
查所有数据 get 返回所有数据
添加数据 post 返回添加的数据
另一个类(含参数)
查看某一条数据 get 返回这一条数据
修改某一条数据 put 返回修改的这条数据
删除某条数据 delete 返回None
补充:
url后面是方法名,当url匹配成功后,再执行方法
三、Serializer
class BookSerialize(serializers.Serializer): title = serializers.CharField(max_length=32) price = serializers.IntegerField() pub_date = serializers.DateField() # 外键 publish = serializers.CharField(source="publish.name") # 多对多 authors = serializers.SerializerMethodField() def get_authors(self, obj): temp = [] for author in obj.authors.all(): temp.append(author.name) return temp
四、ModelSerializer
1、简介
用法与ModelForm相似
2、作用
a、models表与序列化直接关联
b、校验、保存、更新数据
3、自定义字段
publish = serializers.CharField(source="publish.name") def create(self, validated_data): print(validated_data) # {'publish': {'name': '1'}, 'title': 'swift', 'price': 99, 'pub_date': datetime.date(2018, 9, 10), 'authors': [<Author: tom>, <Author: alex>]} book = Book.objects.create(title=validated_data['title'], price=validated_data['price'], pub_date=validated_data['pub_date'], publish_id=validated_data['publish']['name']) book.authors.add(*validated_data['authors']) return book
4、Hyperlink
目的:自定义字段产生link,通过该link,访问某个对应的某个数据
path('publish/<publish_id>/', views.PublishDetailView.as_view(), name="publish_detail"),
class BookModelSerialize(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' publish = serializers.HyperlinkedIdentityField( # url的别名 view_name="publish_detail", # 对应表的字段 lookup_field="publish_id", # url的参数 lookup_url_kwarg="publish_id" )
Add `context={'request': request}` when instantiating the serializer
BookModelSerialize(book_list, many=True, context={'request': request})
五、例子
1、配置文件
restframwork相当于app
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01.apps.App01Config', 'rest_framework', ]
2、模型(储存表关系)
from django.db import models # Create your models here. class Book(models.Model): title = models.CharField(max_length=32) price = models.IntegerField() pub_date = models.DateField() publish = models.ForeignKey("Publish", on_delete=models.CASCADE) authors = models.ManyToManyField("Author") def __str__(self): return self.title class Publish(models.Model): name = models.CharField(max_length=32) email = models.EmailField() def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=32) age = models.IntegerField() def __str__(self): return self.name
3、路由(CBV)
urlpatterns = [ path('admin/', admin.site.urls), path('books/', views.BookView.as_view()), path('books/<book_id>/', views.BookDetailView.as_view()), path('publish/', views.PublishView.as_view()), path('publish/<publish_id>/', views.PublishDetailView.as_view()), ]
4、模型序列化
from rest_framework import serializers from app01.models import Author, Publish, Book # 作者表的序列化 class PublishModelSerialize(serializers.ModelSerializer): class Meta: model = Publish fields = "__all__" class BookModelSerialize(serializers.ModelSerializer): class Meta: model = Book fields = '__all__'
5、视图
from django.shortcuts import render, HttpResponse from rest_framework.views import APIView from app01.serialize import BookModelSerialize, PublishModelSerialize from app01.models import Author, Publish, Book from rest_framework.response import Response # Create your views here. class BookView(APIView): # 查看书籍, 返回所有数据(书籍信息) def get(self, request): book_list = Book.objects.all() book_serialize = BookModelSerialize(book_list, many=True) # return HttpResponse(author_serialize.data) return Response(book_serialize.data) # 添加书籍,并返回改书籍的数据 def post(self, request): # 反序列化 book = BookModelSerialize(data=request.data) if book.is_valid(): book.save() return Response(book.data) else: return Response(book.errors) class BookDetailView(APIView): # 查看某一部书,返回这本书 def get(self, request, book_id): book_obj = Book.objects.filter(pk=book_id).first() book_serialize = BookModelSerialize(book_obj) return Response(book_serialize.data) # 修改书籍, 返回修改后的数据 def put(self, request, book_id): book_obj = Book.objects.filter(pk=book_id).first() # 反序列化 book = BookModelSerialize(book_obj, data=request.data) if book.is_valid(): book.save() return Response(book.data) else: return Response(book.errors) # 删除书籍 返回None def delete(self, request, book_id): Book.objects.filter(pk=book_id).delete() return Response() class PublishView(APIView): # 查看出版社, 返回所有数据(出版社信息) def get(self, request): publish_list = Publish.objects.all() publish_serialize = PublishModelSerialize(publish_list, many=True) # return HttpResponse(author_serialize.data) return Response(publish_serialize.data) # 添加出版社,并返回该出版社的数据 def post(self, request): # 反序列化 publish = PublishModelSerialize(data=request.data) if publish.is_valid(): publish.save() return Response(publish.data) else: return Response(publish.errors) class PublishDetailView(APIView): # 查看某一出版社,返回该出版社 def get(self, request, publish_id): publish_obj = Publish.objects.filter(pk=publish_id).first() publish_serialize = PublishModelSerialize(publish_obj) return Response(publish_serialize.data) # 修改出版社, 返回修改后的数据 def put(self, request, publish_id): publish_obj = Publish.objects.filter(pk=publish_id).first() # 反序列化 publish = PublishModelSerialize(publish_obj, data=request.data) if publish.is_valid(): publish.save() return Response(publish.data) else: return Response(publish.errors) # 删除出版社 返回None def delete(self, request, publish_id): Publish.objects.filter(pk=publish_id).delete() return Response()