django - 使用 Django Rest 框架中定义的 mixins 类

标签 django django-rest-framework django-views

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 这样的对象, ListCreateAPIViewModelViewSet 。不必在所有这些类中实现相同的逻辑,或者使用仅线性的基类的继承,而是可以通过使用实现逻辑的 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/

相关文章:

python - Django 模板 : How to Pass PK/IDs of Displayed Objects Back to the Views. 模板中的 py 文件?

python - 类型对象 'Book' 没有属性 'order_by'

javascript - 尝试在模型上创建“赞”按钮

python - Django rest framework 将 ArrayField 序列化为字符串

python - 类型对象 'Users' 没有属性 '_meta'

javascript - django REST framework 嵌套序列化程序和带有文件的 POST 嵌套 JSON

python - User 类型的对象不是 JSON 可序列化的

sql - Django 中的数据库问题 : can't reset because of dependencies

python - 如何将 zip 文件发送到前端以在 DRF 中下载

python - 从调度方法访问 context_data