I’d like to update a table with Django – something like this in raw SQL:
update tbl_name set name = 'foo' where name = 'bar'
My first result is something like this – but that’s nasty, isn’t it?
list = ModelClass.objects.filter(name = 'bar')
for obj in list:
obj.name = 'foo'
obj.save()
Is there a more elegant way?
Update:
Django 2.2 version now has a bulk_update.
Old answer:
Refer to the following django documentation section
In short you should be able to use:
You can also use
Fobjects to do things like incrementing rows:See the documentation.
However, note that:
ModelClass.savemethod (so if you have some logic inside it won’t be triggered)..update()on a sliced QuerySet, it must be on an original QuerySet so you’ll need to lean on the.filter()and.exclude()methods.