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 ?
Maybe you can try another way, I just got it for my project, using Django 1.8
After looking for a way to check if a model instance can be deleted in django , i came across many sample, but was not working as expected. Hope this solution can help.
Let start by creating an Abstract model class which can be inherited by other model
Example
So let say we have three model Organization and Department and StaffType So many Department can be in an Organization And an Organization has a particular StaffType
so let say after adding some information you want to remove an organization model instance that is already tied to a Department
For instance we have Organization Table => (name = Engineering, pk = 1) Department Table => (name=Developer, organization_fk=1, pk=1)
Now when you try to delete an organization after get it with the pk
With this at hand you can check if it deletable
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:
Documentation
Late reply but this can also be avoided using
model.PROTECT
on the ForeignKeytarget = models.ForeignKey( Target, related_name='sub_targets', on_delete=models.PROTECT )
You can override the model's delete operation like:
Note that it does not work if related object has no reverse relation to the other one.