【问题标题】:Django urls with empty values具有空值的 Django url
【发布时间】:2014-09-30 03:40:57
【问题描述】:

我有一个 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()),

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

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

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

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

【问题讨论】:

    标签: python django django-urls


    【解决方案1】:

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

    希望这是你想要的。

    【讨论】:

    • 实际上那些不是主键。我只是这样命名它们! :D
    • 我试过这个网址:localhost:8000/api/student/Campos/57911101 ...它与我以前的网址一起工作,但在我改成*后,正如你提到的,它没有收到任何东西
    • @crozzfire 嗯,我在控制台上收到 ('Campos', '57911101'),组被捕获..
    • 我做了一个小编辑。 api中的campus_id是与另一个模型的外键关系...忘记加双下划线
    • @crozzfire 是的,我也编辑了答案。如果未提供pk2,它将作为空字符串传递给视图,您需要检查pkpk2 是否为非空,然后再将它们传递给filter()
    猜你喜欢
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多