Django URLs with Null Values

I have a django application where I call api as follows: (api.py)

class studentList(APIView):
    def get(self, request, pk, pk2, format=None):
        student_detail = Student.objects.filter(last_name = pk, campus_id__name = pk2)
        serialized_student_detail = studentSerializer(student_detail, many=True)
        return Response(serialized_student_detail.data)

and in the urls I do something like the following:

url(r'^api/student/(?P<pk>.+)/(?P<pk2>.+)/$', api.studentList.as_view()),

Now the problem is that my application is a function of search , where it sends the parameters pkand pk2in the api. Sometimes a user can select only one of these parameters to perform a search operation . Therefore, when only one parameter is selected, the url will look something like this:

http://localhost:8000/api/student/##value of pk//

or

http://localhost:8000/api/student//##value of pk2/

So, how can I make the request still work, and how to make the URL so that it accepts even these parameters?

+4
source share
1 answer

.* (0 ) .+ ( 1 ):

url(r'^api/student/(?P<pk>.*)/(?P<pk2>.*)/$', api.studentList.as_view()),

:

>>> import re
>>> pattern = re.compile('^api/student/(?P<pk>.*)/(?P<pk2>.*)/$')
>>> pattern.match('api/student/1//').groups()
('1', '')
>>> pattern.match('api/student//1/').groups()
('', '1')

, pk pk2:

class studentList(APIView):
    def get(self, request, pk, pk2, format=None):
        student_detail = Student.objects.all()
        if pk:
            student_detail = student_detail.filter(last_name=pk)
        if pk2:
            student_detail = student_detail.filter(campus_id__name=pk2)

        serialized_student_detail = studentSerializer(student_detail, many=True)
        return Response(serialized_student_detail.data)

, , .

+2

All Articles