如何在模型类中创建与放置并执行功能相对应的自定义操作端点?

时间:2018-12-13 11:24:21

标签: django django-rest-framework

我正在使用Django Rest Framework:v3.7,Django v1.11和Dynamic Rest v1.9.2

我的MyModel类中包含以下内容:

class MyModel():
    # .. fields declared here..

    def change_status(self):
        #... other code not crucial
        allowed = self.status in possible_new_states
        if allowed:
            return self.save()
        return True

我有以下ViewSet

from dynamic_rest.viewsets import DynamicModelViewSet
# from rest_framework.decorators import action # for DRF 3.8
from rest_framework.decorators import detail_route # for DRF 3.7
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

class MyModelViewSet(DynamicModelViewSet):
    """
    VendorQuotations API.
    """
    permission_classes = (IsAuthenticated,)
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    @detail_route(methods=['put']) # use this for DRF 3.7
    # @action(detail=True, methods=['put']) # use this for DRF 3.8 and above
    def status(self, request, pk=None):
        """Update the status."""

以及以下序列化器:

class VendorQuotationSerializer(DynamicModelSerializer):

DynamicModelSerializer继承自serializers.ModelSerializer,而DyanmicModelViewSet继承自viewsets.ModelViewSet

我想让/ my_models /:id / change_status这样的端点指向视图集中的status方法,从而以某种方式在模型级别执行change_status方法。

我查看了django rest文档,并确实复制了change_password的示例,但是我不确定如何将视点与模型之间的点连接起来。

请告知

2 个答案:

答案 0 :(得分:1)

您可以尝试这样:

set hive.msck.repair.batch.size=3000;
set hive.tez.java.opts=-Xmx4g;
set hive.tez.container.size=192400;

答案 1 :(得分:1)

@ruddra的回答很好,但是与其执行自定义查找,不如使用现有的get_object()方法来处理404并检查权限(非常重要!)

from rest_framework import status

# from rest_framework.decorators import action # for DRF 3.8
from rest_framework.decorators import detail_route # for DRF 3.7

@detail_route(methods=['put']) # use this for DRF 3.7
# @action(detail=True, methods=['put']) # use this for DRF 3.8 and above
def status(self, request, pk):
   obj = self.get_object()
   changed_status = obj.change_status()
   return Response({'success':True, "status_changed": changed_status},status=status.HTTP_200_OK)