django rest framework detail_route 在 get 方法中不工作
django rest framework detail_route not working in get method
我使用 ModelViewSet
定义了一个视图集如下
我尝试 redefine GET
方法来做一些事情,比如从 celery 中获取一些东西。但这部分代码不起作用,它的行为就像标准 API 并且没有执行我在 get_job_detail
函数中编写的内容。
如何正确定义"detail_route"函数。
views.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)
urls.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)),
]
现在你的正确 url 是:/job/<pk>/get_job_detail
如果你只想:/job/<pk>
你不需要使用 @detail_route
只需将你的方法重命名为 def retrieve(self, request, *args, **kwargs):
更多详情 retrievemodelmixin one of the part class of the modelviewset
我使用 ModelViewSet
定义了一个视图集如下
我尝试 redefine GET
方法来做一些事情,比如从 celery 中获取一些东西。但这部分代码不起作用,它的行为就像标准 API 并且没有执行我在 get_job_detail
函数中编写的内容。
如何正确定义"detail_route"函数。
views.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)
urls.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)),
]
现在你的正确 url 是:/job/<pk>/get_job_detail
如果你只想:/job/<pk>
你不需要使用 @detail_route
只需将你的方法重命名为 def retrieve(self, request, *args, **kwargs):
更多详情 retrievemodelmixin one of the part class of the modelviewset