Django框架使用视图组件进行接口优化
1.导入mixin
from rest_framework.mixinx import ( ListModelMix, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, RetrieveModelMixin ) from rest_framework.generics import GenericAPIView
2.定义序列化类
class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('title', 'price', 'publish', 'authors', 'author_list', 'publish_name', 'publish_city' ) extra_kwargs = { 'publish': {'write_only': True}, 'authors': {'write_only': True} } publish_name = serializers.CharField(max_length=32, read_only=True, source='publish.name') publish_city = serializers.CharField(max_length=32, read_only=True, source='publish.city') author_list = serializers.SerializerMethodField() # "get_"是固定格式,"get_"后面部分与author_list保持一致,不能随便写 def get_author_list(self, book_obj): # 拿到queryset开始循环 [{}, {}, {}, {}] authors = list() for author in book_obj.authors.all(): authors.append(author.name) return authors
3.导入序列化类
from .app_serializers import BookSerializer
4.定义视图类
class BookView(ListModelMix, CreateModelMixin, GenericAPIView): # queryset和serializer_class是固定的写法 queryset = Book.objects.all() serializer_class = BookSerializer def get(): return self.list() def post(): return self.create()
class BookFilterView(RetrieveModelMixin, DestroyModelMixin, UpdateModelMixin, GenericAPIView): queryset = Book.objects.all() serializer_class = BookSerializer def get(): return self.retrieve() def delete(): return self.destroy() def put(): return self.update()
注意:单条数据操作的url是这样的:re_path(r'books/(?P<pk>\d+)/$, views.BookFilterView.as_view())
5.urls.py文件
from django.urls import re_path from xfzapp import views urlpatterns = [ re_path(r'books/$', views.BookView.as_view()), re_path(r'books/(?P<nid>\d+)/$', views.BookFilterView.as_view()), ]