user996015
user996015

Reputation: 137

Use string as parameter in a function

I'm trying to use a string as a parameter in a function. Is something like this possible?

from django.contrib.auth.models import User

param_var = 'contains'
User.objects.filter(first_name__{param_var}='John')

# ideally, this should equate to:
User.objects.filter(first_name__contains='John')

Upvotes: 1

Views: 111

Answers (2)

user996015
user996015

Reputation: 137

Solved:

# Something like this...
qs = User.objects.all()

parameters = {
    'name': {
        'type': 'get',
        'filter': [
            'first_name__icontains',
            'last_name__icontains',
            # ...
        ],
    },
    # ...
}

for parameter, data in parameters.items():
    if data['type'] == 'get':
        value = request.GET.get(parameter, None)
    elif data['type'] == 'getlist':
        value = request.GET.getlist(parameter)

    if value:
        query = Q()

        for f in data['filter']:
            query = query | Q(**{ f : value })
        qs = qs.filter(query)

Upvotes: 1

retracile
retracile

Reputation: 12339

param_var = 'contains'
User.objects.filter(**{'first_name__%s'%param_var: 'John'})

Though I really wonder about the wisdom of doing that... I think you may be re-inventing sql injection...

I suspect there's a better way. You should probably explain more of what you are trying to accomplish.

Upvotes: 3

Related Questions