Replace Keyword Argument With Variable in Django Model Filtering


I am performing filtering on a django model based on the data supplied by user in an input form. I don’t want to hard-code values and so I would love to loop through the entire query parameters in request.POST and then filter by the key and value.

Here is a sample from my code

class QueryView(View):
    def post(self, request, *args, **kwargs):
        params = request.POST
        if params:
            for key in params:
                queryset = MyModel.objects.filter(key=params[key])
        return MyResponse

I can’t get things to work as key must be a field in MyModel, is there a better way of achieving this same goal.


You can pass them as dictionary:

queryset = MyModel.objects.filter(**{field_name: v1, another_field_name: v2})

Answered By – Sergey Pugach

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published