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.
This commit is contained in:
Alexandru Chirila 2019-01-04 17:07:01 +02:00
parent 030119c117
commit 36d939a151

View File

@ -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