DjangoRestFramework如何重写ModelViewSet get方法

pu3pd22g  于 2023-02-17  发布在  Go
关注(0)|答案(3)|浏览(283)

我有这样一个模型:

class AccountViewSet(viewsets.ModelViewSet):
    """
    A simple ViewSet for viewing and editing accounts.
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    permission_classes = [IsAccountAdminOrReadOnly]

如何重写get方法,以便在单击/api/accounts/8时可以在返回第8个帐户之前添加一些代码?

fhg3lkii

fhg3lkii1#

ModelViewSetmixins.RetrieveModelMixin,当你点击/api/accounts/8时它会调用。你可以从它重写retrieve方法并做额外的工作。

class AccountViewSet(viewsets.ModelViewSet):
    """
    A simple ViewSet for viewing and editing accounts.
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    permission_classes = [IsAccountAdminOrReadOnly]

    def retrieve(self, request, *args, **kwargs):
        #todo anything
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
c7rzv4ha

c7rzv4ha2#

您可以覆盖ActionViewSet的检索方法。

def retrieve(self, request, *args, **kwarge):
    account = self.get_object()
    # write your extra codes here
    serializer = self.get_serializer(instance=account)
    return Response(data=serializer.data, status=status.HTTP_200_OK
    return Response(
wlzqhblo

wlzqhblo3#

可以覆盖retrieve方法。
/api/accounts/8是一个detail API调用,它使用的是retrieve方法。
所以,如果你看一下视图集代码,我们可以找到它。

class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    """
    A viewset that provides default `create()`, `retrieve()`, `update()`,
    `partial_update()`, `destroy()` and `list()` actions.
    """
    pass

溶液

class AccountViewSet(viewsets.ModelViewSet):
    """
    A simple ViewSet for viewing and editing accounts.
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    permission_classes = [IsAccountAdminOrReadOnly]

    def retrieve(self, request, *args, **kwargs):
        # do your stuff - start
        ...
        # end
        return super().retrieve(request, *args, **kwargs):

参考:https://github.com/encode/django-rest-framework/blob/master/rest_framework/viewsets.py

相关问题