I am creating a simple blog site with multi-user facility using django framework. In my project, If the admin deletes any user, all of that user's blogs should not be deleted, I've tried using
models.ForeignKey(django.contrib.auth.models.User,on_delete=models.CASCADE)
but it obviously deletes all the blogs if the admin deletes the user. Can anyone help me please? Thank in advance...
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.
I suggest you to run makemigrations and migrate again because you may have deleted models and tried to delete users. I hope it helps because I have solved my issue like this:
python3 manage.py makemigrations
python3 manage.py migrate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With