pythondjango-rest-frameworkurl-parametersquery-stringurl-pattern

URL pattern for query string parameters Django REST Framework


This is my current url path is as http://localhost:8000/api/projects/abcml/2021 and in the urls.py page I am passing as path("api/projects/<str:project_handle>/<int:year>", functionname...) and in the view, I accept this parameters with self.kwargs.get method.

I want to pass url as this format http://localhost:8000/api/projects/abcml/?year=2021 What changes do I need to make in url pattern?

I tried this path("api/projects/<str:project_handle>/?year=<int:year> but did not seem correct also in the view page, instead of self.kwargs.get I changed it to self.request.query_params.get for year parameter. That did not work either. Error it throwing is Page not found (404).


Solution

  • The query string [wiki] is not part of the path, and therefore can not be matched.

    You thus specify as path:

    path('api/projects/<str:project_handle>/', functionname)
    

    In the view, you can access the data with self.request.GET['year'] and this will return a string or a KeyError in cas the year was not provided in the query string.