简体   繁体   中英

How to pass multiple parameters of unknown length from react to django url

I have to pass multiple parameters to a Django view through Django URL.I am passing the values from React fetch.The list of parameters is variable.For example,it could be 2 sometimes and 3 or 4 sometimes. I have following urls.py file

path('getallvalues/<pk>',views.MultipleValueView.as_view())

views.py

class MultipleValueView(APIView):
    def get(self,request,*args,**kwargs):
        serializer_class=ValueSerializer
        listofvalues=["test","test2"]
        return Response({"weights":getMultipleValueJourney(listofvalues)[0],"years":getMultipleValueJourney(listofvalues)[1]})



React code:

  fetch("http://127.0.0.1:8000/getallvalues/"+valueList)
        .then(response =>  response.json())
        .then(json => {
            var {years,weights}=this.state;
            this.setState({
              
              weights:json.weights,
              years:json.years,
              
              }}

How could I structure my urls.py file?I have seen certain answers from stackoverflow but none of them worked in my scenario.

add query parameters to your fetch call at frontend then at backend, you can get those params and filter based on them like

qp= self.request.GET.get('param_name')
if qp is not None:
    queryset = queryset.filter(some_condition)

In this way, you wouldn't need to add any params in your Django URLs or you can checkout Django filters package if you need something more which is mentioned in DRF's docs as well https://django-filter.readthedocs.io/en/stable/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM