Django Rest Framework 如何覆盖 ModelViewSet 的 get 方法

huangapple go评论65阅读模式
英文:

DjangoRestFramwork how to override ModelViewSet get method

问题

我有一个像这样的模型:

class AccountViewSet(viewsets.ModelViewSet):
    """
    用于查看和编辑帐户的简单视图集。
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    permission_classes = [IsAccountAdminOrReadOnly]

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

英文:

I have a model like this :

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

How do I override the get method so when I hit /api/accounts/8 I can add some code before returning the 8th account ?

答案1

得分: 1

ModelViewSet包含mixins.RetrieveModelMixin,当你访问/api/accounts/8时会调用它。你可以重写它的retrieve方法并进行额外的工作。

class AccountViewSet(viewsets.ModelViewSet):
    """
    用于查看和编辑帐户的简单ViewSet。
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    permission_classes = [IsAccountAdminOrReadOnly]

    def retrieve(self, request, *args, **kwargs):
        # 做任何需要的工作
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)
英文:

ModelViewSet have mixins.RetrieveModelMixin, which call when you hit /api/accounts/8.You can override retrieve method from it and do extra work.

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)

答案2

得分: 0

你可以覆盖ActionViewSet的retrieve方法。

def retrieve(self, request, *args, **kwarge):
    account = self.get_object()
    # 在这里编写额外的代码
    serializer = self.get_serializer(instance=account)
    return Response(data=serializer.data, status=status.HTTP_200_OK
英文:

You can overwrite the retrieve method of your 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(

答案3

得分: 0

retrieve 方法可以被覆盖。

/api/accounts/8 是一个详细的 API 调用。它使用了 retrieve 方法。

所以,如果你看一下 viewset 代码,我们可以找到以下内容。

class ModelViewSet(mixins.CreateModelMixin,
                   mixins.RetrieveModelMixin,
                   mixins.UpdateModelMixin,
                   mixins.DestroyModelMixin,
                   mixins.ListModelMixin,
                   GenericViewSet):
    """
    提供默认的`create()`,`retrieve()`,`update()`,
    `partial_update()`,`destroy()``list()`操作的 viewset
    """
    pass

解决方案

class AccountViewSet(viewsets.ModelViewSet):
    """
    用于查看和编辑账户的简单 ViewSet
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
    permission_classes = [IsAccountAdminOrReadOnly]

    def retrieve(self, request, *args, **kwargs):
        # 进行你的操作 - 开始
        ...
        # 结束
        return super().retrieve(request, *args, **kwargs):

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

英文:

You can override the retrieve method.

/api/accounts/8 is a detail api call. It uses the retrieve method.

So, If you look at the viewset code. we can find that.

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

solution

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

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

huangapple
  • 本文由 发表于 2023年2月14日 01:22:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定