[Answer]-How can I fix the following Django code? Using variables within function command

1👍

Couple things should be fixed:

  • you need to pass objs into the function
  • in order to pass keyword arguments made from strings, use argument unpacking
  • no need for ; at the end of lines

Here’s the fixed version:

def condition(objs, radio, **kwargs):
    if radio == 'equal to':
        filters = {'%s__icontains' % key: value for key, value in kwargs.iteritems()}
        objs = objs.filter(**filters)
    if radio == 'not equal to':
        filters = {'%s__icontains' % key: value for key, value in kwargs.iteritems()}
        objs = objs.exclude(**filters)
    return objs

Usage:

if name:
    objs = condition(objs, radio_name, name=name)
if number:
    objs = condition(objs, radio_number, number=number)

This still has room for improvement, but I hope it helps to achieve the desired results.

👤alecxe

0👍

When you say “it’s not working,” I’m a bit unclear on what the expected result is and what’s actually happening. Looking over your code, one thing that jumps out is that you’re checking radio == ‘equal to’ and so on — if what you’re feeding into it is a radio button object you probably have to refer to the value property of that object, e.g.:

if radio.value == 'equal to':
    objs = objs.filter(var__icontains=var)

Is the “radio” class one you built yourself, or something you’re importing? If the former, you may want to consider adding a “type” field to it, so the second bit of code you put in would look like this:

if radio.type == 'name':
    objs = condition(radio_name, name)
elif radio.type == 'number':
    objs = condition(radio_number, number)

By the way, you don’t need semicolons at the end of your lines if you’re writing in Python; I removed them in the above code.

Leave a comment