Alexey Alexey - 1 month ago 7
reST (reStructuredText) Question

Deletion objects that is used as foreign key

I have next models:

class Target(models.Model):
name = models.CharField(max_length=100, blank=False)


class SubTarget(models.Model):
target = models.ForeignKey(Target, related_name='sub_targets')
name = models.CharField(max_length=100, blank=True, null=True, default='')


For example, I run next code:

target = Target(name='test-target')
target.save()
sub_target = SubTarget(name='test-sub-target, target=target)
sub_target.save()


So now I have sub_target object with foreign key.

My serializer for target looks like:

class TargetSerializer(serializers.ModelSerializer):
class Meta:
model = Target
fields = ('id', 'name', 'sub_targets')
depth = 1
read_only_fields = ('sub_targets',)


and appropriate view:

class TargetDetail(generics.RetrieveUpdateDestroyAPIView):
model = Target
serializer_class = TargetSerializer


So, nothing prevents me from deletion just target created object with foreign key. Moreover, this operation delete also related sub_target object. How can I avoid this behaviour ?

Answer

I'm not sure, but I think you're asking how to prevent SubTarget objects from being deleted when you delete Target objects. By default Django emulates ON DELETE CASCADE. You can control this behavior with the on_delete key word.

So:

class Target(models.Model):
    name = models.CharField(max_length=100, blank=False)


class SubTarget(models.Model):
    target = models.ForeignKey(Target, related_name='sub_targets', 
                               null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=100, blank=True, null=True, default='')

Documentation

Comments