YCode
YCode

Reputation: 1272

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

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

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

Upvotes: 2

Views: 1907

Answers (1)

Brian Destura
Brian Destura

Reputation: 12068

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.

Upvotes: 5

Related Questions