Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 246
Alexey Avatar asked Oct 30 '14 16:10

Alexey


People also ask

What happens if foreign key is deleted?

A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.

Can foreign key be deleted?

Alternatively, you can also delete a Foreign Key Constraint from the SQL Server Management Studio itself. You can try it if the commands do not work. Expand your database view. Right Click on Table which has foreign key constraint.

Can we delete a row with foreign key?

Here, ON DELETE CASCADE is added because when any row is deleted in one table the same gets deleted in the foreign referenced tables that are referencing the primary key in that table.


1 Answers

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

like image 67
joshua Avatar answered Oct 05 '22 03:10

joshua