How do you set the default value for Django's 'on_delete=models.SET_DEFAULT'

Viewed 533

In the example below, how--and where--do you set the default value?

author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT)

1 Answers

For SET_DEFAULT to work, default should be used in the ForeignKey declaration:

author = models.ForeignKey('Author', on_delete=models.SET_DEFAULT, default=None, null=True)

In this case, whatever is set as default will be used when the related object is deleted.

EDIT: As pointed out by @MojixCoder and @Ersain, in this example you need to set null=True otherwise deleting the instance of the ForeignKey will cause IntegrityError to be raised.

Related