Pass kwargs into Django Filter

11,932

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.

Share:
11,932
Kervvv
Author by

Kervvv

A programmer is going to the grocery store and his wife tells him, "Buy a gallon of milk, and if there are eggs, buy a dozen." The programmer leaves, buys everything, and drives back home. The wife asks him "Why in the world did you buy 13 gallons of milk?" The programmer says, "There were eggs." Later he goes to pick up some dry cleaning. His wife told him, "While you're out, pick up some bread." He never came home..

Updated on June 27, 2022

Comments

  • Kervvv
    Kervvv almost 2 years

    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.