问题
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