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

老子叫甜甜 提交于 2019-12-11 06:48:53

问题


I am have recently started learning DjangoRestFramework and I came across two ways to create model instances, one is through Django Rest Framework CreateAPIView and the other is CreateModelMixin. So I wanted to know what is the difference between them and also between the other mixins and Views which perform identical functions.


回答1:


Here's the difference: mixins are (as described in the code comments) the basic building blocks for generic class based views - they're basically view-agnostic python objects, which means you won't be able to use a CreateModelMixin alone to actually create a model. You need to inherit that on a new view, and the CreateAPIView does exactly that:

# 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)

The same concept applies to all other mixins and views provided, mixins are reusable pieces of code.

This is a great (long, but great) read on that matter, really thorough.



来源:https://stackoverflow.com/questions/55711549/what-is-the-difference-between-a-class-based-view-createview-and-the-mixing-crea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!