和一级视图相比:
GenericAPIView
来自 : from rest_framework.generics import GenericAPIView
新增:
字段:
queryset=BookInfo.objects.all()
self.queryset 本来可以获取但是编译器不让你获取 还是用方法获取吧
self.get_queryset()
serializer_class=BookInfoSerializer
self.serializer_class
lookup_field = 'pk' #下面讲解get_object使用
方法:
self.get_serializer(instance=books,many=True)
self.serializer_class()(instance=books,many=True)
self.get_queryset()
self.get_object() 自动通过queryset和pk获取单个实例
使用
views.py
class BookInfoGenericView(GenericAPIView): queryset=BookInfo.objects.all() serializer_class=BookInfoSerializer def get(self,request): books = self.get_queryset() # books = self.queryset # serializers = self.get_serializer(instance=books,many=True) # serializers = self.serializer_class()(instance=books,many=True) serializers = self.get_serializer(instance=books,many=True) return Response(serializers.data) def post(self,request): book = request.data serializer = BookInfoSerializer(data=book) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) class BookInfoGenericDetailView(GenericAPIView): queryset = BookInfo.objects.all()# 也是必须填写 后面的get_object()是从这里获取 serializer_class = BookInfoSerializer def get(self,request,pk): # 参数只能是pk book = self.get_object()# 自动从传入的pk获取 serializers = self.get_serializer_class()(instance=book) return Response(serializers.data,status=status.HTTP_200_OK) # 更新单个 def put(self,request,pk): book_data = request.data book = self.get_object() serializer = self.get_serializer_class()(instance=book,data=book_data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) # 删除单个 def delete(self,request,pk): self.get_object().delete() return Response(status=status.HTTP_204_NO_CONTENT)
urls.py
path('generic_view_books/', views.BookInfoGenericView.as_view()), path('generic_view_books/<int:pk>', views.BookInfoGenericDetailView.as_view()),
注意的是:路由和视图函数值必须是pk 因为默认是pk 如果想要其他的是可以修改
get_object 是如何通过pk获取
自己也去源码看
self.kwargs