我想在实现ListCreateAPIView
的基于类的视图中覆盖create方法,而不是通常在访问诸如get_queryset(self)
方法,请求,URL **kwargs
之类的覆盖方法时覆盖来自self
,但是我想覆盖.create()
的{{1}}方法,所以我看了一下代码来寻找签名,CreateModelMixin
django传递了什么此功能的create(self, request, *args, **kwargs)
?这些网址**kwargs, *args
是不是偶然?我该如何在通用视图中覆盖create方法,因为可以从**kwargs
访问通用视图的任何功能中的request
,但是create函数的签名明确需要一个请求参数。>
答案 0 :(得分:2)
以下是DRF ListCreateAPIView,如您所见,*args, **kwargs
是直接从标准post
方法传来的:
class ListCreateAPIView(mixins.ListModelMixin,
mixins.CreateModelMixin,
GenericAPIView):
"""
Concrete view for listing a queryset or creating a model instance.
"""
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
现在,从create
覆盖CreateModelMixin
,您可以简单地将其覆盖为:
from rest_framework import generics
class YourWonderfulView(generics.ListCreateAPIView):
queryset = YourModelClass.objects.all()
serializer_class = YourSerializer
def create(self, request, *args, **kwargs): # don't need to `self.request` since `request` is available as a parameter.
# your custom implementation goes here
return Response(response) # `response` is your custom response – e.g. dict, list, list of dicts etc
希望它会有所帮助:)
答案 1 :(得分:1)
from rest_framework import generics
from tasks.models import Task
from tasks.serializers import TaskSerializer
class TaskList(generics.ListCreateAPIView):
queryset = Task.objects.all()
serializer_class = TaskSerializer
def create(self, request, *args,**kwargs):
# your implementation
return Response(response)