Django 'on_delete' models?


When you get something like this with your old code.

File "<frozen importlib._bootstrap>", line 1014, in _gcd_import

File "<frozen importlib._bootstrap>", line 991, in _find_and_load

File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked

File "<frozen importlib._bootstrap>", line 671, in _load_unlocked

File "<frozen importlib._bootstrap_external>", line 783, in exec_module

File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed

File "/home/sites/vacaturestoday/permanentjob/", line 97, in <module>

class JobApplication(models.Model):

File "/home/sites/vacaturestoday/permanentjob/", line 100, in JobApplication

job = models.ForeignKey('PermanentJob')

TypeError: __init__() missing 1 required positional argument: 'on_delete'

When the object referenced by the ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete parameter. For example, if you have a nullable ForeignKey and you want it to be set to null when the referenced object is deleted:

CASCADE: When the referenced object is deleted, also delete the object referencing it (for example, when you delete a blog post, you may also want to delete comments). SQL equivalent: CASCADE.

PROTECT: Forbids deleting the referenced object. To delete it, you must manually delete all objects referencing it. SQL equivalent: RESTRICT.

RESTRICT: (Introduced in Django 3.1) PROTECT-like behavior that more accurately matches SQL's RESTRICT. (see django documentation example)

SET_NULL: Set the reference to NULL (requires the field to be nullable). For example, when you delete a user, you might want to keep his comment on a blog post, but say it was posted by an anonymous (or deleted) user. SQL equivalent: SET NULL.

SET_DEFAULT: Set the default value. SQL equivalent: SET DEFAULT.

SET(...): Set the given value. This is not part of the SQL standard and is handled entirely by Django.

DO_NOTHING: Probably a really bad idea, as this creates integrity issues in your database (referencing objects that don't actually exist). SQL equivalent: no operation.

So, you have to update your model ForeignKey.