jahmed31
jahmed31

Reputation: 3766

Difference between null=True and on_delete=models.SET_NULL django

I have a field

owner = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)

What is the difference between these two attributes on model field ?

Upvotes: 11

Views: 13366

Answers (3)

Aubdur Rob Anik
Aubdur Rob Anik

Reputation: 86

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.

Upvotes: 4

Manas Mishra
Manas Mishra

Reputation: 45

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)

Upvotes: 2

Milad Khodabandehloo
Milad Khodabandehloo

Reputation: 1977

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.

Upvotes: 26

Related Questions