Search code examples
pythondjangoobjectmodels

Django objects being "non subscriptable" leads me to write redundant code


Django objects aren't "subscriptable" meaning if you have user.name you can't define it with user['name'] meaning you can't dynamically load up an object with info.

info = {'first_name': 'Artur', 'last_name': 'Sapek'}

me = User()
for i in info:
    me[i] = info[i]

brings up TypeError: 'User' object is not subscriptable and I find myself writing code like

info = {'first_name': 'Artur', 'last_name': 'Sapek'}

if 'first_name' in info: me.first_name = info['first_name']
if 'last_name' in info: me.first_name = info['last_name']
so on...

(It requires if-statements as well because there is more info and it is not always complete - this isn't my actual code)

Is there any better way to do this with Django objects, which don't have the flexibility to use bracket notation like you can with lists, dicts, and strings?


Solution

  • setattr is what you're looking for.

    In your case you could do something like this:

    for attr, value in info.items():
        setattr(me, attr, value)