Home > Mobile >  Django REST Framework, implications of [] in search
Django REST Framework, implications of [] in search

Time:06-28

I have a very basic Django API which makes a query in elasticsearch. The output shows the query_parameters and the search.query.

Why I cannot pass the country variable in this case 'DE' to the search.query as shown in the output? Could you please explain the implications of [] in country[]?

class ESNumView(APIView):
    """Obtain number of articles after a search in titles and abstract in ES"""

    def get(self, request, *args, **kwargs):
        query = self.request.query_params.get('query')
        country = self.request.query_params.get('country')

        print(self.request.query_params)

        search = Search(index=constants.ES_INDEX)

        q = Q('bool',
              must=[
                Q('multi_match', query=query, fields=['title', 'abstract']),
                Q('terms', country=country)
              ]
            )
        s = search.query(q)

        pprint(s.to_dict())

        num_count = s.count()

        return Response(data=[{'search_count': num_count}])

The output is;

 <QueryDict: {'query': ['membrane'], 'country[]': ['DE']}>

 {'query': {'bool': {'must': [{'multi_match': {'fields': ['title', 'abstract'], 'query': 'membrane'}}, {'terms': {'country': None}}]}}}

CodePudding user response:

The name of the key is country[], that's all. So you access the value with:

country = self.request.query_params.get('country[]')

The [] part is thus not special in any way: the key simply ends with [ and ] as characters.

The reason this happens is likely because the HTML form has a multiselect on country values, and for PHP, this had to be done by letting the name end with [] to "push" the values on the list. But this is not the case for Django.

Since it however ends with [], it thus likely means that the user is supposed to be able to select mutliple countries. In that case you can use .getlist(…) [Django-doc] to obtain a list of associated values:

countries = self.request.query_params.getlist('country[]')  # ['DE']

You will then thus need to update the query logic accordingly.

  • Related