Issue
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?
Solution
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:
ModelClass.objects.filter(name='bar').update(name="foo")
You can also use F
objects to do things like incrementing rows:
from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
See the documentation.
However, note that:
- This won't use
ModelClass.save
method (so if you have some logic inside it won't be triggered). - No django signals will be emitted.
- You can't perform an
.update()
on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the.filter()
and.exclude()
methods.
Answered By - jb.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.