Skip to content

Instantly share code, notes, and snippets.

@reddytocode
Created August 12, 2025 12:55
Show Gist options
  • Save reddytocode/96db400538101d29e3169abab6a8a534 to your computer and use it in GitHub Desktop.
Save reddytocode/96db400538101d29e3169abab6a8a534 to your computer and use it in GitHub Desktop.
class ModelSerializer(Serializer):
def update(self, instance, validated_data):
raise_errors_on_nested_writes('update', self, validated_data)
info = model_meta.get_field_info(instance)
# Simply set each attribute on the instance, and then save it.
# 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.
m2m_fields = []
for attr, value in validated_data.items():
if attr in info.relations and info.relations[attr].to_many:
m2m_fields.append((attr, value))
else:
setattr(instance, attr, value)
instance.save(update_fields=list(validated_data.keys())) # This is the modified line on the model serializer
# Note that many-to-many fields are set after updating instance.
# Setting m2m fields triggers signals which could potentially change
# updated instance and we do not want it to collide with .update()
for attr, value in m2m_fields:
field = getattr(instance, attr)
field.set(value)
return instance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment