Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ForeignKey Constraint Failed error

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...

like image 972
Kamlesh Gupta Avatar asked Sep 03 '26 03:09

Kamlesh Gupta


2 Answers

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:

  1. CASCADE: delete referring objects;
  2. PROTECT: do not allow to delete the user given there are objects that refer to the user;
  3. SET_NULL: set to NULL (None in Python), in that case, one has to set null=True in the ForeignKey(..) constructor;
  4. SET_DEFAULT: sets the ForeignKey back to the default=... value;
  5. SET(..): set the ForeignKey to some value that is passed to the SET(..) constructor (one can also use a callable);
  6. 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.

like image 154
Willem Van Onsem Avatar answered Sep 04 '26 17:09

Willem Van Onsem


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
like image 42
zoro Avatar answered Sep 04 '26 16:09

zoro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!