django-rest-framework中如何在通用视图(例如:ListCreateAPIView)中覆盖.create()方法?

时间:2018-06-28 18:24:56

标签: python django django-rest-framework django-views

我想在实现ListCreateAPIView的基于类的视图中覆盖create方法,而不是通常在访问诸如get_queryset(self)方法,请求,URL **kwargs之类的覆盖方法时覆盖来自self,但是我想覆盖.create()的{​​{1}}方法,所以我看了一下代码来寻找签名,CreateModelMixin django传递了什么此功能的create(self, request, *args, **kwargs)?这些网址**kwargs, *args是不是偶然?我该如何在通用视图中覆盖create方法,因为可以从**kwargs访问通用视图的任何功能中的request,但是create函数的签名明确需要一个请求参数。

2 个答案:

答案 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)