基于 Class 的视图 CreateView 和混合 CreateModelMixin 之间有什么区别

What is the difference between a Class Based View CreateView and the mixing CreateModelMixin

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

区别如下:mixins 是(如代码注释中所述)basic building blocks for generic class based views - 它们基本上是与视图无关的 python 对象,这意味着您不会能够单独使用 CreateModelMixin 来实际创建模型。您需要在新视图上继承它,而 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)

相同的概念适用于所有其他 mixinsviewsmixins 可重复使用的代码片段 .

This 是一本关于这个问题的好书(很长,但很棒),非常透彻。