Reputation: 121
This question might be a stupid one, but I need to validate it from the SO community.
I have 2 models.
class Address(models.Model):
name = models.CharField(max_length=100)
area = models.ForeignKey(Area, null=True)
class Area(models.Model):
name = models.CharField(max_length=20)
Now If I want to delete one instance of Address, will it delete the instance of Area object it is pointing to as a Foreign key?
address = Address.objects.filter(...).delete()
PS: I know the on_delete functionality in Django.It is required when a foreign key object is deleted and to prevent those objects pointing to this foreign key, this parameter is used. In my case, scenario is reverse.
Upvotes: 2
Views: 4120
Reputation: 4504
The Area
will not be affected. However, if you deleted the Area
, the Address
will be deleted (as the default on_delete
behaviour is cascade).
Upvotes: 1
Reputation: 770
This is a common doubt for one who starts to learn the database operations.
As you have mentioned there is on_delete in django which is different.
First we should understand what a Foreign key is. It is another table in which a set of data is stored. Say we have an entry for address1 with area as area1. Similarly I create an address address2 with same area area1. Now if the deletion of address1 deletes area1 also then the relation concept of the other instance is not attained. That is in general Foreign key just defines a new model in the database. You will have to remove the FK instance by overriding the default method. Else it wont delete the FK instance.
Upvotes: 1
Reputation: 4346
No, It will not delete Area
row, because its a foreignkey field.
So on deleting Address instance, corresponding area
instance will not be deleted, unless you override delete
method of the model to delete the instance.
Upvotes: 1