2

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 ?

Mesh
  • 130
  • 2
  • 11

1 Answers1

3

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.

Mounir
  • 11,306
  • 2
  • 27
  • 34
  • That make sense, but why it was perfect on django 1.x ?, what if I want keep user as text just like django 1.x ? – Mesh Jun 19 '19 at 07:40
  • I do not think that was working, it only means there was no database constraint enforced, for example with myIsam mysql database – Mounir Jun 19 '19 at 11:49
  • https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.DO_NOTHING – Mounir Jun 19 '19 at 11:53