Mixins类的实际用途是什么?我实在不明白。所有 mixins 类(如 CreateModelmixin、Listmixin 等功能)都已在基于类的 View (如 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/时我看到 CreateModelMishing 中可用的方法如下:
def create(self, request, *args, **kwargs):
def get_success_headers(self, data):
def perform_create(self, serializer):
这些方法在ListCreateApiView中已经有了,那为什么Django还要去创建这个无用的类呢?
最佳答案
ListCeateAPIView
类使用 CreateModelMixin
混合。事实上,看看 Ancestors (Method Resolution Order; MRO) of the ListCreateAPIView
[classy-drf] 。它包含CreateModelMixin
.
大多数APIView
Django 制作的只是一个 APIView
和一堆 mixin。这些 mixins 定义了实际的行为。 ListCreateAPIView
(以及 APIView
的其他子类)只是 mixin 包,而 APIView
.
这也是 mixin 的用例:在类中混合某些逻辑。有多个APIView
允许创建像 CreateAPIView
这样的对象, ListCreateAPIView
和 ModelViewSet
。不必在所有这些类中实现相同的逻辑,或者使用仅线性的基类的继承,而是可以通过使用实现逻辑的 mixin 将其混合在所有层次结构中.
如果您想要构造 APIView
的子类,那么使用这些 mixins 也很有用。你自己做了一些复杂的事情,同时混合了 create
的逻辑。处理不做如此复杂的事情。
但是,如果您使用 mixin,它通常写在基类之前,因此:
# mixin first 🖟
class ExampleView(<strong>mixins.CreateModelMixin</strong>, ListAPIView):
# …
这是必要的,因为 mixin 通常可以覆盖现有方法,因此 mixin 在 MRO 中应优先于基类。
关于django - 使用 Django Rest 框架中定义的 mixins 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71111159/