How passing string on filter keyword to Django Objects Model?

前端 未结 1 844
春和景丽
春和景丽 2020-12-31 12:10

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

I have:

my_object = MyModel.objects.filter(my_keyword =my_filter_values)
相关标签:
1条回答
  • 2020-12-31 12:22

    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 讨论(0)
提交回复
热议问题