Django URL 的空值问题

4 投票
1 回答
4352 浏览
提问于 2025-04-18 16:20

我有一个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/

那么我该如何让查询仍然有效,并且如何构建一个网址,使其能够接受这些参数呢?

1 个回答

3

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

希望这正是你想要的。

撰写回答