使用 Django rest 框架中定义的 mixins class

use of mixins class defined in Django rest framework

Mixins的实际用途是什么class?我真的不明白。所有 mixins classes,如 CreateModelmixin、Listmixin 等功能都已在基于 class 的视图(如 ListCreateApiView)中可用。

例如:

class ExampleView(ListCreateAPIView
                 DestroyAPIView,
               RetrieveUpdateAPIView):
    queryset = Example.objects.all()
    serializer_class = ExampleSerializer
    pagination_class = CustomPageNumberPagination

使用 mixins 我们可以通过以下方式做到这一点:

class ExampleView(ListAPIView,
                     mixins.CreateModelMixin):
        queryset = Example.objects.all()
        serializer_class = ExampleSerializer
        pagination_class = CustomPageNumberPagination

当我检查 https://www.cdrf.co/ 时,我看到 CreateModelMixing 中可用的方法如下:

def create(self, request, *args, **kwargs): 
def get_success_headers(self, data): 
def perform_create(self, serializer):

这些方法在ListCreateApiView中已经有了,那为什么Django还要去创建这个没用的class??

ListCeateAPIView class 使用 CreateModelMixin mixin。确实,看看 Ancestors (Method Resolution Order; MRO) of the ListCreateAPIView [classy-drf]。它包含 CreateModelMixin.

Django 制作的大多数 APIView 只是一个 APIView 和一堆混音。这些混合定义了实际的行为。 ListCreateAPIView(以及 APIView 的其他子 class)只是混合包和 APIView.

这也是mixin的use-case:在class中混合某些逻辑。有多个 APIView 允许创建像 CreateAPIViewListCreateAPIViewModelViewSet 这样的对象。与其在所有这些 classes 中实现相同的逻辑,或者使用仅 linear 的 base-class 的继承,不如将其混合在所有层次结构中通过使用实现逻辑的 mixin。

如果你想自己构建一个 APIView 的子 class 来做一些复杂的事情,那么使用这些 mixins 也很有用,同时混合逻辑create 句柄不会做如此复杂的事情。

但是,如果您使用 mixin,那通常写在 beforebase class,所以:

#              mixin first 🖟
class ExampleView(<strong>mixins.CreateModelMixin</strong>, ListAPIView):
    # …

这是必要的,因为 mixin 通常可以覆盖现有方法,因此 mixin 应该在 MRO 中优先于基础 class。