How To Pass Argument Name As A Parameter?
I have this code: hobbies2 = form.cleaned_data.pop('hobbies2') PersonneHobby.objects.filter(personne=obj).delete() for pk_str in hobbies2: try: hobby = TagTraduit.objec
Solution 1:
You could do it with an arbitary number of keyword-arguments (**
) and insert calculated additional parameters inside the function:
def update_field(field, update_this, **kwargs):
...
kwargs[update_this] = TagTraduit.objects.get(pk=int(pk_str))
p = field.objects.create(**kwargs)
...
this allows you to call it like that:
update_field(PersonneHobby, 'hobby', personne=obj)
update_field(PersonneProgramme, 'programme', personne=obj)
Solution 2:
You can do this:
def update_field(..., field_name):
...
tag = TagTraduit.objects.get(pk=int(pk_str))
p = PersonneProgramme.objects.create(**{'personne': obj, field_name: tag})
Solution 3:
I will go with what @MSeifert said. If you want whatever you have written to work, I mean with positional arguments alone.
def f(a,b,c):
a.func(b=b,c=c)# this is perfectly legal
But the better way to go about it is,
deff(a, **kwargs):
a.func(**kwargs) # kwargs is passed as a dict. **kwargs is# unpacking it into key1=val1, key2=val2, ...
Post a Comment for "How To Pass Argument Name As A Parameter?"