如果get请求接受具有字母值的jobCategoryId
,我想用我的自定义消息创建404 Not Found错误响应。
请求格式:
GET /JobProfilesByCategory/:jobCategoryId
views.py:
class JobProfilesByCategoryView(generics.ListAPIView):
"""
A custom view to create a view for Job profile by Category. Lookup_url_kwarg fetches the jobCategoryId variable from the URL
"""
model=JobProfiles
serializer_class = JobProfilesByCategorySerializer
lookup_url_kwarg = "jobCategoryId"
def get_queryset(self):
jobCategoryId = self.kwargs.get(self.lookup_url_kwarg)
print(jobCategoryId)
if(any(c.isalpha() for c in jobCategoryId)):
return Response({"detail":"Not Found"},status=status.HTTP_404_NOT_FOUND)
else:
queryset = JobProfiles.objects.filter(jobCategoryId=jobCategoryId)
return queryset
urls.py:
url(r'JobProfilesByCategory/(?P<jobCategoryId>[-\w]+$)',view=views.JobProfilesByCategoryView.as_view()),#6th API
答案 0 :(得分:2)
您可以使用NotFound
from rest_framework.exceptions import NotFound
...
def get_queryset(self):
jobCategoryId = self.kwargs.get(self.lookup_url_kwarg)
print(jobCategoryId)
if (any(c.isalpha() for c in jobCategoryId)):
raise NotFound({"custom_key": "Custom Error Message"})
else:
queryset = JobProfiles.objects.filter(jobCategoryId=jobCategoryId)
return queryset