我是 Django 的新手,我对 Django 的自定义方法有点困惑apiview。在 ApiView 中,如何创建自定义方法以及如何从 axios 调用。
例如
这是我的观点
class TimeSheetAPIView(APIView):
@action(methods=['get'], detail=False)
def getbytsdate(self, request):
return Response({"timesheet":"hello from getbydate"})
def get(self,request,pk=None):
if pk:
timesheet=get_object_or_404(TimeSheet.objects.all(),pk=pk)
serializer = TimeSheetSerializer(timesheet)
return Response({serializer.data})
timesheet=TimeSheet.objects.all()
serializer = TimeSheetSerializer(timesheet,many=True)
return Response({"timesheet":serializer.data})
Run Code Online (Sandbox Code Playgroud)
这是我的网址=>
url(r'^timesheets_ts/(?P<pk>\d+)/$', TimeSheetAPIView.as_view()),
url(r'^timesheets_ts/', TimeSheetAPIView.as_view()),
Run Code Online (Sandbox Code Playgroud)
通常我的网址会像=>
api/timesheet_ts/
Run Code Online (Sandbox Code Playgroud)
这个将得到我所有的记录。
所以我的问题是如何设置 URLgetbytsdate或getbyname其他某种自定义获取方法?我该如何打电话?
我尝试这样=>
url(r'^timesheets_ts/getbytsdate/(?P<tsdate>[-\w]+)/$', TimeSheetAPIView.as_view()),
Run Code Online (Sandbox Code Playgroud)
我就这样打电话
api/timesheets_ts/getbytsdate/?tsdate='test'
Run Code Online (Sandbox Code Playgroud)
它不起作用。
那么请您解释一下apiviewurl 设置中的自定义方法吗?
除了您的实现之外,您只需向您的urls.py. 编辑你的urls.py如下:
# urls.py
timesheet_getbytsdate_detail = TimeSheetAPIView.as_view({'get': 'getbytsdate'})
timesheet_detail = TimeSheetAPIView.as_view({'get': 'retrieve'})
urlpatterns = [
url(r'^timesheets_ts/getbytsdate/(?P<tsdate>[-\w]+)/$', getbytsdate_detail),
url(r'^timesheets_ts/(?P<pk>[0-9]+)/', timesheet_detail),
]
Run Code Online (Sandbox Code Playgroud)
编辑:您需要使用组合viewsets.GenericViewSet而mixins.RetrieveModelMixin不是APIVew使用它:
class TimeSheetAPIView(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
@action(methods=['get'], detail=False)
def getbytsdate(self, request):
return Response({"timesheet":"hello from getbydate"})
def retrieve(self, request, *args, **kwargs):
timesheet=self.get_object()
serializer = TimeSheetSerializer(timesheet)
return Response({serializer.data})
timesheet=TimeSheet.objects.all()
serializer = TimeSheetSerializer(timesheet,many=True)
return Response({"timesheet":serializer.data})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5601 次 |
| 最近记录: |