88

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

1
  • 1
    Gotta love StackOverflow. The problem you're struggling with was solved 10 years ago XD. Commented Mar 24, 2022 at 16:52

2 Answers 2

209

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 })
Sign up to request clarification or add additional context in comments.

5 Comments

This may be the best answer I've seen in a long time.
Or in reference to your django model: Members_Model.objects.filter(**{ filter: search_string })
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?
Ok another question can this string have more than one keys and variables incorporate all variables?
@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?
-3

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")

1 Comment

this is just a standard filter, has nothign to do witht he question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.