[Answered ]-Django modify objects using key=value options

1๐Ÿ‘

โœ…

A more efficient way to do this is with:

id = 123
attribute = 'title'
value = 'New Title'
Stuff.objects.filter(id=id).update(**{attribute: value})

This will prevent first fetching the object with a query, and then update it.

If you need to load the object anyway, you can work with setattr(โ€ฆ) [Python-doc]:

id = 123
attribute = 'title'
value = 'New Title'

item = Stuff.objects.get(id=id)
setattr(item, attribute, value)
item.save()

0๐Ÿ‘

Try using an if statement like

If attribute = 'title'
    item.title = value
    item.save()
๐Ÿ‘คChymdy

Leave a comment