1

我使用ModelViewSet如下定义了一个视图集

我试图重新定义GET方法来做一些事情,比如从 celery 获取东西。但是这部分代码是行不通的,它就像一个标准的API,并没有做我在get_job_detail函数中写的东西。

我应该如何正确定义“detail_route”函数。

视图.py

class JobViewSet(viewsets.ModelViewSet):
    queryset = job.objects.all()
    serializer_class = JobSerializer

    @detail_route(methods=['get'])
    def get_job_detail(self, request, pk=None):
        # print('these part wont proceed')
        job_item = self.get_object()
        if job_item.isReady or job_item.isSuccessful:
            return Response(self.serializer_class(job_item).data)
        celeryjob = sometask.AsyncResult(pk)
        celeryjob.get()
        if celeryjob.state == 'SUCCESS':
            job_item.state = celeryjob.state
            job_item.result = celeryjob.result
            job_item.isReady = True
            job_item.isSuccessful = True
            job_item.save()
        if celeryjob.state == 'FAILURE':
            job_item.state = celeryjob.state
            job_item.result = celeryjob.result
            job_item.isReady = True
            job_item.isSuccessful = False
            job_item.save()
        return Response(self.serializer_class(job_item).data)

网址.py

from django.conf.urls import url, include

from apply_api import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'job',views.JobViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
]
4

1 回答 1

1

现在您的正确网址是:/job/<pk>/get_job_detail如果您只想:/job/<pk>您不需要使用@detail_route将您的方法重命名为def retrieve(self, request, *args, **kwargs):更多详细信息retrievemodelmixin modelviewset的部分类之一

于 2017-08-30T13:25:18.957 回答