[Solved]-Difference between null=True and on_delete=models.SET_NULL django

26👍

null=True means owner field can be null in the database which means you can make an object of your model that has no owner.
on_delete=models.SET_NULL
means if the owner of an existing object got deleted set this field for existing object to null.

4👍

SET_NULL argument of the ForeignKey on_delete option is only available to you when you have set the null option on the ForeignKey field to True.

After use null=True and on_delete=models.SET_NULL, when a deletion happens to the referenced object then the value of the referencing object will be updated as NULL. So a NULL value will be placed for the referencing object.

2👍

null=True means that the field could be empty or null, but on_delete=models.SET_NULL is being used to take of the presence of the owner of the field, that it should be set to NULL if the owner is not present.

class Product(models.Model):
    name = models.CharField(max_length = 50)
    category = models.ForeignKey(Category, on_delete=models.SET_NULL)

Leave a comment