在django rest框架的基于类的视图中,我们默认使用get,post等函数。除此之外,是否可以添加我们自己的函数?如果有可能我们将如何在网址中引用它。
我需要的功能
def get_user_by_name(request, name, format=None):
jobseekers = JobSeeker.objects.filter(name=name)
serializer = JobseekerSerializer(jobseekers, many=True)
return Response(serializer.data)
def get_user_by_email(request, email, format=None):
jobseekers = JobSeeker.objects.filter(email=email)
serializer = JobseekerSerializer(jobseekers, many=True)
return Response(serializer.data)
def get_user_by_school(request, school, format=None):
schools = SchoolDetails.objects.filter(school=school)
jobseekers = JobSeeker.objects.filter(email=email)
serializer = JobseekerSerializer(jobseekers, many=True)
return Response(serializer.data)
def get_user_by_email(request, email, format=None):
jobseekers = JobSeeker.objects.filter(email=email)
serializer = JobseekerSerializer(jobseekers, many=True)
return Response(serializer.data)
答案 0 :(得分:1)
在视图中传递type
变量,并使用可用的HTTP方法。由于看起来您正在检索数据,因此通常使用GET方法,但您可以如实地使用您想要的任何方法。 GET方法允许您将变量放在URL中,如果这是您想要的。
将type变量放入请求后,您只需使用if
语句来确定如何处理它。
您还可以为每种类型的请求创建不同的视图,尽管这可能有点过分。
这是假设使用GET方法的一个例子:
class foo(APIView):
# This uses the GET method. POST, PUT, PATCH etc. would use
# def post(...), def put(...)...
def get(self, request, format=None):
# Check what type of request is being made and return the proper response.
if request.POST['type'] == 'get_user_by_name':
jobseekers = JobSeeker.objects.filter(name=request.POST['name'])
serializer = JobseekerSerializer(jobseekers, many=True)
return Response(serializer.data)
elif request.POST['type'] == 'get_user_by_email':
jobseekers = JobSeeker.objects.filter(email=email)
serializer = JobseekerSerializer(jobseekers, many=True)
return Response(serializer.data)
elif ...