Home > database >  In Django Query set using filter with custom arguments
In Django Query set using filter with custom arguments

Time:07-16

I am using the filter in Django queryset, as it takes arguments like:

Model.objects.filter(name="Amit")

here is name and it's value, I am getting from the request of API:

def get(self, request):
    column = request.query_params.get('column')
    val = request.query_params.get('value')
    query = Data.objects.filter(column=val).values()
    serializer = DataSerializer(query, many=True).data
    return Response(serializer)

but here column [inside filter] is not getting recognized as the request parameter, it is taken as the column name of the table which is not available.

The error I got:

django.core.exceptions.FieldError: Cannot resolve keyword 'column' into field.

Hope this information is suitable for understanding the problem, if something is missing please let me know and kindly help me out with this.

CodePudding user response:

You can try this: django-query-filter-with-variable-column

so if collum is a variable containing which field you want to filter then it should be like this:

def get(self, request):
    column = request.query_params.get('column')
    val = request.query_params.get('value')
    query = Data.objects.filter(**{column:val}).values()
    serializer = DataSerializer(query, many=True).data
    return Response(serializer)

and you should check if column or val is not None for prevent error.

  • Related