开发者

How passing string on filter keyword to Django Objects Model?

开发者 https://www.devze.com 2023-03-31 17:10 出处:网络
How can i pass variables on a keywordobject filter on a view? I have: my_obj开发者_StackOverflow社区ect = MyModel.objects.filter(my_keyword =my_filter_values)

How can i pass variables on a keyword object filter on a view?

I have:

my_obj开发者_StackOverflow社区ect = MyModel.objects.filter(my_keyword =my_filter_values)

I want to grab my_keyword from a variable coming from a string, like this:

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

But this doesn't work because Django doesn't know my_string from MyModel.

Edit: I've found this SO question - I'll test and report back.


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

Which would result in getting all objects with a price >= 10. And if you want to query on more than one field, you can just add another line below my_filter[my_keyword]:

my_filter[my_keyword] = my_filter_value
my_filter[my_other_keyword] = my_other_filter_value
0

精彩评论

暂无评论...
验证码 换一张
取 消