#7298 closed (fixed)
update() on a sliced query set updates all objects.
Reported by: | Sebastian Noack | Owned by: | nobody |
---|---|---|---|
Component: | Database layer (models, ORM) | Version: | dev |
Severity: | Keywords: | qsrf-cleanup | |
Cc: | Russell Keith-Magee, Malcolm Tredinnick | Triage Stage: | Unreviewed |
Has patch: | yes | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
What do think following code will do?
model.objects.all()[:1].update(foo='bar')
No it won't update the first object in the model, it will update all objects. Although I expected that it updates the first object, we should just prevent the user from doing this. Because of (at least MySql) do not support offset for UPDATE. It supports limit but their might be DBMS which do not support both on UPDATE and if you think about this use case, it is a real corner case. But anyway the user should not destroy his data by accident. I have written a patch which adds the same sanity check to QuerySet.update() as already done when calling QuerySet.order_by().
Attachments (2)
Change History (7)
by , 17 years ago
Attachment: | 0001-Preventing-update-on-a-sliced-QuerySet-7298.patch added |
---|
comment:1 by , 16 years ago
Keywords: | qsrf-cleanup added |
---|
by , 16 years ago
Attachment: | prevent_update_queryset_r7599.patch added |
---|
Prevents updates on querysets, patched against r7599
comment:2 by , 16 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
comment:3 by , 16 years ago
QuerySet.update() bypasses custom Model.save() methods. If this is intended behaviour the docs should mention it. Otherwise there had to be code to iterate the queryset anyway (manually updating each object) that could be applied to sliced querysets as well.
comment:4 by , 16 years ago
Not only overriden save() methods are bypassed, also the pre_save() method of fields are ignored. But at first, this has nothing to do with this ticket. And at second, the update() method is not a shortcut for, following:
for obj in query_set: obj.foo = 'bar' obj.save()
The update() method is intended to be a low level API to the UPDATE sql statement, to enable updating multiple objects at once with a single query. Maybe the documentation should explain this more clearly, if required.
I think this patch is the right approach, I've only expanded it slightly by adding it in to the other update-like method on querysets, and cleaned up the wording a bit.