一:GenericAPIView
(1)特点:
(1)其继承APIVies,使用完全兼容APIView
(2)其在APIView之上又添加了新的功能
(2)使用方式
(3)单取
# 路由层 urlpatterns = [ url(r‘^v2/books/$‘, views.BookGenericAPIView.as_view()), url(r‘^v2/books/(?P<pk>.*)/$‘, views.BookGenericAPIView.as_view()), ]
# 视图层def get(self, request, *args, **kwargs): # 传统的群查方式 单查同样 此处不列举 book_query = models.Book.objects.all().filter(is_delete=False) book_ser = serializers.BookModelSerializer(book_query, many=True) data = book_ser.data return APIResponse(results=data)
def get(self, request, *args, **kwargs): # GenericAPIView 方式取值 book_query = self.get_queryset() # 获取序列化对象 book_ser = self.get_serializer(book_query,many=True) # 进行序列化 book_data = book_ser.data # 获取数据 return APIResponse(results=book_data)
PS:
(1)此种方式会报错 没有获取queryset对象
(2)没有获取序列化类
queryset = models.Book.objects.filter(is_delete=False) serializer_class = serializers.BookModelSerializer def get(self, request, *args, **kwargs): # GenericAPIView 方式取值 book_query = self.get_queryset() # 获取序列化对象 book_ser = self.get_serializer(book_query,many=True) # 进行序列化 book_data = book_ser.data # 获取数据 return APIResponse(results=book_data)
PS:
(1)get_queryset():从类属性queryset中获得model的queryset数据
(2)get_object():从类属性queryset中获得model的queryset数据,再通过有名分组pk确定唯一操作对象
(3)get_serializer():从类属性serializer_class中获得serializer的序列化类
# 单取 lookup_field = ‘pk‘ # 可以通过该方法自定义主键名称 def get(self, request, *args, **kwargs): book_query = self.get_object() book_ser = self.get_serializer(book_query) book_data = book_ser.data return APIResponse(results=book_data)
原文地址:https://www.cnblogs.com/SR-Program/p/11706332.html
时间: 2024-11-09 06:27:00