This is due to the on_delete=CASCADE
. That means that if the object to which the ForeignKey
refers is deleted, then it should delete the referring object as well. Such CASCADE
can thus result in a large amount of objects that get deleted, since the deletion of objects can in fact trigger other deletes, and so on.
There are several options, listed in the documentation:
CASCADE
: delete referring objects;
PROTECT
: do not allow to delete the user given there are objects that refer to the user;
SET_NULL
: set to NULL
(None
in Python), in that case, one has to set null=True
in the ForeignKey(..)
constructor;
SET_DEFAULT
: sets the ForeignKey
back to the default=...
value;
SET(..)
: set the ForeignKey
to some value that is passed to the SET(..)
constructor (one can also use a callable);
DO_NOTHING
: here we keep a reference, but some database backend will not allow that, since these check FOREIGN KEY
constraints.
So we can for example use SET_NULL
, and thus set the author
to NULL
/None
in case we delete the author:
from django.db import models
from django.conf import settings
class Post(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
null=True,
on_delete=models.SET_NULL
)
# ...
It is also better to use settings.AUTH_USER_MODEL
, since if you later change the User
model, this will automatically change the reference to the new model.
SET_NULL
instead ofCASCADE
– Chowchow