From f2f5daf83133ff8c5d8f770b6acbfe21e2b3d555 Mon Sep 17 00:00:00 2001 From: Anton Shevchenko Date: Wed, 8 Mar 2017 22:14:48 -0500 Subject: [PATCH 1/3] Use 'update_fields' to limit the object's save() method to just the order field, so that other fields are not accidentally overwritten with stale data. --- adminsortable/admin.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/adminsortable/admin.py b/adminsortable/admin.py index f67505a..ee92501 100644 --- a/adminsortable/admin.py +++ b/adminsortable/admin.py @@ -298,7 +298,8 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): for index in indexes: obj = objects_dict.get(index) setattr(obj, order_field_name, start_index) - obj.save() + # only update the object's order field + obj.save(update_fields=(order_field_name,)) start_index += step response = {'objects_sorted': True} except (KeyError, IndexError, klass.DoesNotExist, From eb5a9e0a8a921df7cbe8c8e2d900101e5e5f20ef Mon Sep 17 00:00:00 2001 From: Anton Shevchenko Date: Wed, 8 Mar 2017 23:28:40 -0500 Subject: [PATCH 2/3] Avoid unnecessary db queries: perform the update iff the order field has changed. --- adminsortable/admin.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/adminsortable/admin.py b/adminsortable/admin.py index ee92501..2991f5c 100644 --- a/adminsortable/admin.py +++ b/adminsortable/admin.py @@ -297,9 +297,11 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): for index in indexes: obj = objects_dict.get(index) - setattr(obj, order_field_name, start_index) - # only update the object's order field - obj.save(update_fields=(order_field_name,)) + # perform the update iff the order field has changed + if getattr(obj, order_field_name) != start_index: + setattr(obj, order_field_name, start_index) + # only update the object's order field + obj.save(update_fields=(order_field_name,)) start_index += step response = {'objects_sorted': True} except (KeyError, IndexError, klass.DoesNotExist, From eb5f14fe2272c841cad6557ef99c585dcad57bed Mon Sep 17 00:00:00 2001 From: Anton Shevchenko Date: Sat, 11 Mar 2017 11:20:16 -0500 Subject: [PATCH 3/3] Clarify comment. --- adminsortable/admin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/adminsortable/admin.py b/adminsortable/admin.py index 2991f5c..ae24dd1 100644 --- a/adminsortable/admin.py +++ b/adminsortable/admin.py @@ -297,7 +297,7 @@ class SortableAdmin(SortableAdminBase, ModelAdmin): for index in indexes: obj = objects_dict.get(index) - # perform the update iff the order field has changed + # perform the update only if the order field has changed if getattr(obj, order_field_name) != start_index: setattr(obj, order_field_name, start_index) # only update the object's order field