Ejonas Ejonas - 1 year ago 68
Python Question

Using named arguments as variables

I am using django but I think this question primarily belongs to Python itself.

I have something like:

def get(self, request, arg, *args, **kwargs):

if kwargs['m0'] == 'death':
if kwargs['m1'] == 'year':
result = Artists.objects.filter(death_year=arg)
elif kwargs['m1'] == 'month':
result = Artists.objects.filter(death_month=arg)
elif kwargs['m1'] == 'day':
result = Artists.objects.filter(death_day=arg)
elif kwargs['m0'] == 'birth':
if kwargs['m1'] == 'year':
result = Artists.objects.filter(birth_year=arg)
elif kwargs['m1'] == 'month':
result = Artists.objects.filter(birth_month=arg)
elif kwargs['m1'] == 'day':
result = Artists.objects.filter(birthh_day=arg)

is a named argument that is a field in my model
representing a column in my database. The variables 'm0' and
are passed from the
to my get function (it is actually a
method in my view class).
Can I control the name value of the variable
without using an if else if chain (i.e. make it
)? Since I have many choices, I will have to use a ridiculously very long conditional chain that leads to this same line but with just a different named argument.

I strongly doubt that you should understand this whole problem to answer the question. The original question is simple: Can I use a named argument and its corresponding value as variables in Python?

Answer Source

From what I can make out you can construct the key and then pass in an arg to construct the dict, then include that in the filter

key = '%s_%s' % (kwargs['m0'], kwargs['m1'])
result = Artists.objects.filter(**{key: arg})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download