How to pass a filter keyword string to a Django object model?

How to pass variables in a keyword filter object in a view?

I have:

my_object = MyModel.objects.filter(my_keyword =my_filter_values) 

I want to grab my_keyword from a variable coming from a string, for example:

 my_string = 'my_keyword' my_object = MyModel.objects.filter(my_string=my_filter_values) 

But this does not work, because Django does not know my_string from MyModel .

Edit: I found this SO question - I will test and report.

+4
source share
1 answer

You can do something like this:

 my_filter = {} my_filter[my_keyword] = my_filter_value my_object = MyModel.objects.filter(**my_filter) 

As an example, your variables might be:

 my_keyword = 'price__gte' my_filter_value = 10 

This will get all the objects using price >= 10 . If you want to request more than one field, you can simply add another line below my_filter[my_keyword] :

 my_filter[my_keyword] = my_filter_value my_filter[my_other_keyword] = my_other_filter_value 
+13
source

Source: https://habr.com/ru/post/1369265/


All Articles