87

I am trying to filter a queryset using

info=members.filter(name__contains=search_string)

The problem I have is I do not know which field the user wants to search ahead of time so I need to substitute 'name' with a variable as in

variable_column = 'name'
search_type = 'contains'
filter = variable_column + '__' + search_type
info=members.filter(filter=search_string)

How do I do that?

Rich

Rich
  • 1,769
  • 3
  • 20
  • 30

2 Answers2

206

Almost there..

members.filter(**{'string__contains': 'search_string'})

To understand what it's doing, google around : ) Understanding kwargs in Python

** expands dictionary key/value pairs to keyword argument - value pairs.

To adapt your example to the solution:

variable_column = 'name'
search_type = 'contains'
filter = variable_column + '__' + search_type
info=members.filter(**{ filter: search_string })
Community
  • 1
  • 1
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245
  • 3
    This may be the best answer I've seen in a long time. – Chris Hawkes Jul 18 '15 at 02:10
  • 1
    Or in reference to your django model: Members_Model.objects.filter(**{ filter: search_string }) – jonincanada Aug 05 '15 at 14:43
  • 1
    Ok, really old question, I know, but: Doesn't the use of the name filter both as the object manager method and the key in the dict cause problems? – Malik A. Rumi Jun 03 '19 at 17:42
  • Ok another question can this string have more than one keys and variables incorporate all variables? – Faiz Hameed May 08 '20 at 09:14
  • @Rich @jonincanada- Searching for possibilty of using _variable_ in place of fields struck upon this nice solution. Now if I want to **pass the model name** also as a `variable`, **how would I do that**? – Love Putin Not War Jun 19 '20 at 07:42
-2

Syntax:

model_name.objects.filter(column_name='value')

Ex: In my scenario, I wanted to find out all records with status completed from the Student table.

Student.objects.filter(status="completed")
Viraj Wadate
  • 5,447
  • 1
  • 31
  • 29