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.
CodePudding user response:
You can pass them as dictionary:
queryset = MyModel.objects.filter(**{field_name: v1, another_field_name: v2})
CodePudding user response:
you can access the POST fields and values as request.POST.items()
it would return a key value pair so you can do some thing like this
class QueryView(View):
def post(self, request, *args, **kwargs):
params = request.POST
if params:
for key, value in params.items():
# key is the field and value is it's value
# now you can filter as you wish
queryset = MyModel.objects.filter(key=value)
return MyResponse