Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: use namedtuple instead of dict for **kwargs?

why would this succeed

qs = Model.objects.filter(pk=1)
kwargs = {'name': 'me',
           'age_desc': 'getting older'
}
qs.update(**kwargs)

but not this?

qs = Model.objects.filter(pk=1)
nt =  collections.namedtuple('nt','name, age_desc')
kwargs = nt('me', 'getting older') 
qs.update(**kwargs)

Is there no way to use namedtuples instead of dicts when it come to unpacking parameters in django?

like image 954
LarsVegas Avatar asked Mar 05 '15 19:03

LarsVegas


1 Answers

I don't think Python keyword argument unpacking (the ** syntax) supports named tuples, but you can use the _asdict() method of named tuple objects to get a dictionary from a named tuple. Or vars() on 3.x, and possibly on 2.7.5 (Get the object name of a specific object from namedtuple has some discussion of the state of 2.7.5 installations).

like image 141
Peter DeGlopper Avatar answered Nov 14 '22 23:11

Peter DeGlopper