基于类的视图 CreateView 和混合的 CreateModelMixin 有什么区别

Sau*_*gan 1 mixins django-rest-framework

我最近开始学习 DjangoRestFramework,我遇到了两种创建模型实例的方法,一种是通过 Django Rest Framework CreateAPIView,另一种是 CreateModelMixin。所以我想知道它们之间以及执行相同功能的其他混合和视图之间有什么区别。

hen*_*aro 5

区别在于:mixins是(如代码注释中所述)basic building blocks for generic class based views- 它们基本上是与视图无关的 Python 对象,这意味着您将无法CreateModelMixin单独使用 a来实际创建模型。您需要在新视图上继承它,并且CreateAPIView确实如此:

# Concrete view classes that provide method handlers
# by composing the mixin classes with the base view.

class CreateAPIView(mixins.CreateModelMixin,
                    GenericAPIView):
    """
    Concrete view for creating a model instance.
    """
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

相同的概念适用于所有其他mixinsviews提供mixins可重用代码段

是一篇关于这件事的很棒的(很长但很棒)的读物,非常彻底。