Skip to content

Commit b655fda

Browse files
committed
When updating an instance with foreign key relations, the objects linking to the instance should not be deleted. Instead, the foreign key should simply be removed from the objects to the instance. This commit checks if the related field is a foreign key, and, if so, it unlinks the object. If the field cannot be null, the object gets deleted.
1 parent 87a1476 commit b655fda

File tree

1 file changed

+6
-0
lines changed

1 file changed

+6
-0
lines changed

drf_writable_nested/mixins.py

+6
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,12 @@ def delete_reverse_relations_if_need(self, instance, reverse_relations):
333333
# Remove relations from m2m table
334334
m2m_manager = getattr(instance, field_source)
335335
m2m_manager.remove(*pks_to_delete)
336+
elif related_field.many_to_one and related_field.null:
337+
# The instance should not be deleted if the object is foreign-key related.
338+
unlink_foreign_key = {
339+
related_field.name: None,
340+
}
341+
model_class.objects.filter(pk__in=pks_to_delete).update(**unlink_foreign_key)
336342
else:
337343
model_class.objects.filter(pk__in=pks_to_delete).delete()
338344

0 commit comments

Comments
 (0)