From 36d939a1517341496482d158c87895d769fef979 Mon Sep 17 00:00:00 2001 From: Alexandru Chirila Date: Fri, 4 Jan 2019 17:07:01 +0200 Subject: [PATCH] Use the update_fields argument when saving the instance. By doing so, this will trigger a query with only the specified field, which is: a. More efficient b. Prevents some race conditions. --- rest_framework/serializers.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 110ffbfa9..438860889 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -974,13 +974,15 @@ class ModelSerializer(Serializer): # Note that unlike `.create()` we don't need to treat many-to-many # relationships as being a special case. During updates we already # have an instance pk for the relationships to be associated with. + update_fields = [] for attr, value in validated_data.items(): if attr in info.relations and info.relations[attr].to_many: field = getattr(instance, attr) field.set(value) else: setattr(instance, attr, value) - instance.save() + update_fields.append(attr) + instance.save(update_fields=update_fields) return instance