9

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.

Community
  • 1
  • 1
Kervvv
  • 751
  • 4
  • 14
  • 27

1 Answers1

28

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.

levi
  • 22,001
  • 7
  • 73
  • 74
  • Thanks for your response. 2 questions: do the `**` apply to the `your_filters` variable letting Django know that this can change? If so, isn't that what a variable already does, it varies? Question#2: Let's say I put 'placeholders' on the front end, how could I translate the user's selection back to the view. An AJAX call perhaps? – Kervvv Aug 04 '16 at 22:05
  • @Kervvv about your question 2: yes, you can pass it using ajax and reading them from request.POST or request.GET data, depending what do you want. I din't understand the first question. – levi Aug 04 '16 at 22:15
  • 1
    @levi, Is there anyway I can add "OR" statements inside the kwarg filters? – Christopher Oct 02 '19 at 06:39
  • @Christopher use [Q](https://docs.djangoproject.com/en/2.2/topics/db/queries/#complex-lookups-with-q-objects) objects in django and pipes. `Q(question__startswith='Who') | Q(question__startswith='What')` – levi Oct 02 '19 at 16:13