# The filter backend classes to use for queryset filtering filter_backends = api_settings.DEFAULT_FILTER_BACKENDS
# The style to use for queryset pagination. # pagination_class就是和分页组件相关的类,默认为drf配置中的组件 pagination_class = api_settings.DEFAULT_PAGINATION_CLASS
defget_queryset(self): # 这里断言就是为了说明在继承这个类时,一定要有queryset属性或覆盖这个方法 assert self.queryset isnotNone, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) # 获取ORM对象 queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset
defget_serializer_class(self): # 继承这个类时,一定要有serializer_classt属性或覆盖这个方法 assert self.serializer_class isnotNone, ( "'%s' should either include a `serializer_class` attribute, " "or override the `get_serializer_class()` method." % self.__class__.__name__ )
classViewSetMixin: @classonlymethod # 对as_view()方法又一次封装,action表示可以接收参数了 defas_view(cls, actions=None, **initkwargs): ifnot actions: raise TypeError("The `actions` argument must be provided when " "calling `.as_view()` on a ViewSet. For example " "`.as_view({'get': 'list'})`")
defview(request, *args, **kwargs): self = cls(**initkwargs) # We also store the mapping of request methods to actions, # so that we can later set the action attribute. # eg. `self.action = 'list'` on an incoming GET request. self.action_map = actions
# Bind methods to actions # This is the bit that's different to a standard view # method, action退出action为一个字典,{'get':'list'} for method, action in actions.items(): # handler为实例中的各个方法 handler = getattr(self, action) # 这里setattr相当于metmod == handler setattr(self, method, handler)
if hasattr(self, 'get') andnot hasattr(self, 'head'): self.head = self.get