Capturing URL parameters in request.GET

后端 未结 13 1085
说谎
说谎 2020-11-22 08:30

I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the

13条回答
  •  借酒劲吻你
    2020-11-22 09:04

    Someone would wonder how to set path in file urls.py, such as

    domain/search/?q=CA
    

    so that we could invoke query.

    The fact is that it is not necessary to set such a route in file urls.py. You need to set just the route in urls.py:

    urlpatterns = [
        path('domain/search/', views.CityListView.as_view()),
    ]
    

    And when you input http://servername:port/domain/search/?q=CA. The query part '?q=CA' will be automatically reserved in the hash table which you can reference though

    request.GET.get('q', None).
    

    Here is an example (file views.py)

    class CityListView(generics.ListAPIView):
        serializer_class = CityNameSerializer
    
        def get_queryset(self):
            if self.request.method == 'GET':
                queryset = City.objects.all()
                state_name = self.request.GET.get('q', None)
                if state_name is not None:
                    queryset = queryset.filter(state__name=state_name)
                return queryset
    

    In addition, when you write query string in the URL:

    http://servername:port/domain/search/?q=CA
    

    Do not wrap query string in quotes. For example,

    http://servername:port/domain/search/?q="CA"
    

提交回复
热议问题