Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query filter with variable column

Tags:

django

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

like image 748
Rich Avatar asked Jan 18 '11 02:01

Rich


1 Answers

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 }) 
like image 101
Yuji 'Tomita' Tomita Avatar answered Oct 02 '22 09:10

Yuji 'Tomita' Tomita