Reputation: 305
I have a general question about designing Django models and considering the effect that has on a cascade delete. Suppose the following simple design of an Asset Management app.
class Asset(models.Model):
aquire_date = models.DateField()
cost = models.DecimalField(max_digits=16, decimal_places=2)
description = models.CharField(max_length=30)
account = models.ForeignKey(Account)
vendor = models.ForeignKey(Vendor)
department = models.ForeignKey(Department)
class Vendor(models.Model):
name = models.CharField(max_length=70)
city = models.CharField(max_length=50
phone = PhoneNumberField()
email = models.EmailField()
class Account(models.Model):
account_number = models.IntegerField()
description = models.CharField(max_length=50)
class Department(models.Model):
number = models.IntegerField(unique=True)
name = models.CharField(max_length=50)
So each Asset has 3 ForeignKey fields to other tables. Reading the Django documentation it says 'any objects which had foreign keys pointing at the object to be deleted will be deleted along with it'. I read that to mean if I delete a Department object, the Asset object, or objects, the ForeignKey is referring to will be deleted as well. But if I delete an Asset, the Department, Vendor, and Account remains.
Is that the correct way to understand cascade deletes in Django?
What I would prefer is
Is that possible?
Upvotes: 1
Views: 565
Reputation: 2162
Yes, your understanding is correct.
Solution: When creating a model ForeignKey
field, supply on_delete=django.db.models.SET_NULL
. You need to combine this with null=True
to allow this because the default is False
.
Upvotes: 3