Django的网址为空值

时间:2014-08-07 02:45:20

标签: python django django-urls

我有一个django应用程序,我按如下方式调用api:(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)

并在网址中我做了类似的事情:

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

现在问题是我的应用有一个搜索功能,它将参数pkpk2发送到api。有时,用户可以仅选择其中一个参数来执行搜索操作。因此,当只选择一个参数时,网址将如下所示:

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

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

那么我将如何使查询仍然有效?如何创建一个url,使其甚至接受这些作为参数?

1 个答案:

答案 0 :(得分:2)

使用.*(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')

请注意,现在,您应该在视图中处理pkpk2的空字符串值:

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)

希望这是你想要的。