Django - Get query parameter list

后端 未结 4 1969
自闭症患者
自闭症患者 2020-12-29 10:14

I\'ve an endpoint

http://127.0.0.1:8000/auction/?status=[\'omn\',\'aad\']

I need to get the status list, hence I do the following

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-29 10:33

    Expanding on @DanielRoseman's answer.

    The correct way would be to pass each variable as described: http://127.0.0.1:8000/auction/?status=omn&status=aad.

    However, if you're using modern Javascript frameworks (Vue, Angular, React) there's a good chance you're passing params as an object (e.g., if you're working with axios, VueResource, etc). So, this is the work around:

    Front-end:

    let params = {
       status: ['omn', 'aad',]
    }
    
    return new Promise((resolve, reject) => {
      axios.get(`/auction/`, { params: params }, }).then(response => {
          resolve(response.data);
      }).catch(error => {
          resolve(error.response);
      });
    });
    

    This will then dispatch to Django as the following URL:

    [05/Aug/2019 10:04:42] "GET /auction/?status[]=omn&status[]=aad HTTP/1.1" 200 2418
    

    Which can then be picked up in the corresponding view as:

    # Before constructing **parameters, it may neccessary to filter out any supurfluous key, value pair that do not correspond to model attributes:
    parameters['status__in'] = request.GET.getlist('status[]')
    
    # Using parameters constructed above, filter the Auctions for given status:
    auctions = Auction.objects.filter(is_active=True)
    
    auctions = auctions.filter(**parameters)
    

提交回复
热议问题