Search code examples
djangodjango-rest-frameworkdjango-filter

How to pass dynamic lookups from the request.GET right to filter in DRF?


Sending query like this /?field1=value1 in the request.GET I have {'field1': ['value1']}.

So doing .filter(**request.GET) I send to it (field1=['value1']) instead of (field1='value1').

How I can take strings instead of arrays?


Solution

  • You can make use of the .dict() [Django-doc] to convert it to a dictionary. In case a key contains multiple values, for example with ?field1=value1&field1=value2, it will take the last value.

    For example:

    >>> QueryDict('field1=value1').dict()
    {'field1': 'value1'}
    >>> QueryDict('field1=value1&field1=value2').dict()
    {'field1': 'value2'}
    

    You thus can for example pass this to a function with some_func(**request.GET.dict()).