Django - Get query parameter list

后端 未结 4 1954
自闭症患者
自闭症患者 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条回答
  • 2020-12-29 10:27

    Don't send it in that format in the first place. The standard way of sending multiple values for a single HTML is to send the parameter multiple times:

    http://127.0.0.1:8000/auction/?status=omn&status=aad
    

    which will correctly give you ['omn','aad'] when you use request.GET.getlist('status').

    0 讨论(0)
  • 2020-12-29 10:30

    request.GET['status'] would return you ['omn', 'aad'].

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-29 10:38

    Here is the documentation of HTTPRequest and HTTPResponse

    Request Response Objects

    0 讨论(0)
提交回复
热议问题