FOREIGN KEY constraint failed because of models.DO_NOTHING

Viewed 1544

I have this snippet of code for models.py

class Provider(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING)
    provider = models.CharField(max_length=100, unique=True)
    active = models.BooleanField(default=True)

when ever I tried to delete an object I faced an error says :

django.db.utils.IntegrityError: FOREIGN KEY constraint failed

I faced this issue on django 2.x , since every thing was perfect on 1.11. I made a little search I found may this issue happen by this part on_delete=models.DO_NOTHING, So how could I fix it with kepping every thing as it is ?

1 Answers

Basically you're telling Django to do nothing when you delete a user. So you will try to delete the row which has a related foreign key, this is expected behavior. If you want to keep the provider model even when the user got deleted you have to make user nullable and use models.SET_NULL. If provider has non sense in your logic you can then cascade. If you need to reassign to a default user you can use custom method.

Related