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 ?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With