Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass kwargs into Django Filter

When viewing model entries from within Django Admin, you can specify filters. How can I mimic this behavior? Not to familiar with kwargs but something similar to this:

foo = Model.objects.filter(**__exact='**')

where the first set of ** would be a field in the model and the second set would be an entry. Basically making the queries variable, based on what the user chooses on the front end. How would I send that variable sort option to the view, and then return it back to the webpage. What about using a dictionary? Please help

This SO question has proven to be a little helpful, but still cannot grasp it completely.

like image 931
Kervvv Avatar asked Aug 04 '16 21:08

Kervvv


1 Answers

You can unpack a python dict as your filter parameters using **

your_filters = {
'field_1__exact': value_1,
'field_2__gte': value_2,
}

Model.objects.filter(**your_filters)

Said that, you can built your query filters(a python dict) dynamically based on an user input.

like image 158
levi Avatar answered Sep 20 '22 12:09

levi