drf-writable-nested icon indicating copy to clipboard operation
drf-writable-nested copied to clipboard

Fixes unexpected deletion of related objects.

Open gibsonbailey opened this issue 6 years ago • 6 comments

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 still gets deleted, as it does in the current state of the master branch.

gibsonbailey avatar Dec 24 '19 01:12 gibsonbailey

Codecov Report

Merging #97 into master will increase coverage by 0.01%. The diff coverage is 100%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master      #97      +/-   ##
==========================================
+ Coverage   98.59%   98.61%   +0.01%     
==========================================
  Files           3        3              
  Lines         213      216       +3     
==========================================
+ Hits          210      213       +3     
  Misses          3        3
Impacted Files Coverage Δ
drf_writable_nested/mixins.py 98.52% <100%> (+0.02%) :arrow_up:

Continue to review full report at Codecov.

Legend - Click here to learn more Δ = absolute <relative> (impact), ø = not affected, ? = missing data Powered by Codecov. Last update 87a1476...771a4f7. Read the comment docs.

codecov-io avatar Dec 24 '19 01:12 codecov-io

@gibsonbailey Thanks for the contribution. Could you please add a failing test which is fixed with your changes?

ruscoder avatar Dec 25 '19 03:12 ruscoder

Yes, thanks for the consideration.

gibsonbailey avatar Dec 26 '19 23:12 gibsonbailey

@ruscoder Test has been added. Thanks Vadim!

gibsonbailey avatar Jan 01 '20 21:01 gibsonbailey

@gibsonbailey Thanks for the tests.
I'm not sure that this logic should work in this way. Let's consider how Django works with null=True and on_delete=CASCADE. https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ForeignKey.on_delete

With CASCADE, Django deletes the instance if the related instance is deleted. To avoid this you should pass SET_NULL/SET_DEFAULT.

So, I think the logic should be changed to use on_delete param instead of null

ruscoder avatar Jan 12 '20 03:01 ruscoder

My comment is still actual. So I don't close it and don't accept for now.

ruscoder avatar May 26 '21 17:05 ruscoder