Django query filter with variable column

Django

Django Problem Overview


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

Django Solutions


Solution 1 - Django

Almost there..

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

To understand what it's doing, google around : ) https://stackoverflow.com/questions/1769403/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 })

Solution 2 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRichView Question on Stackoverflow
Solution 1 - DjangoYuji 'Tomita' TomitaView Answer on Stackoverflow
Solution 2 - DjangoViraj WadateView Answer on Stackoverflow