Updating multiple objects at once
Sometimes you want to set a field to a particular value for all the objects in a QuerySet
. You can do this with the update()
method. For example:
# Update all the headlines with pub_date in 2007. Entry.objects.filter(pub_date__year=2007).update(headline='Everything is the same')
You can only set non-relation fields and ForeignKey
fields using this method. To update a non-relation field, provide the new value as a constant. To update ForeignKey
fields, set the new value to be the new model instance you want to point to. For example:
>>> b = Blog.objects.get(pk=1) # Change every Entry so that it belongs to this Blog. >>> Entry.objects.all().update(blog=b)
The update()
method is applied instantly and returns the ...
Get Mastering Django: Core now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.