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
- when an Asset is deleted, no department, vendor, or account is deleted;
- when a Department is deleted, no Asset is deleted, but all ForeignKey fields that point to that Department are set to null.
Is that possible?
Yes, your understanding is correct.
Solution: When creating a model
ForeignKeyfield, supplyon_delete=django.db.models.SET_NULL. You need to combine this withnull=Trueto allow this because the default isFalse.