简体   繁体   中英

Cannot delete some instances of model because of FK

Python 3.6 and Django 1.11.7.

I've got two Models look like the following:

class User():
    name = models.CharField()
    ...

class UserInfo():
   user = models.OneToOneField(User, on_delete=models.PROTECT, primary_key=True, related_name='info')

I wanted to delete some user instance A, and I explicitly deleted user A's info. But when I tried to delete the user model user.delete() , I got the ProtecedError :

ProtectedError: ("Cannot delete some instances of model 'User' because they are referenced through a protected foreign key: 'UserInfo.user'", <QuerySet [<UserInfo: UserInfo object>]>)

Then I tried to put the delete inside a try/catch looks like follows:

try:
    user.delete()
except ProtectedError:
    UserInfo.objects.filter(user=user).delete()
    user.delete()

But still got the same exception. What might went wrong in my operation?

You are using a protect clause on the related objects:

on_delete=models.PROTECT

You can check it in the documentation on:

https://docs.djangoproject.com/en/2.2/ref/models/fields/#django.db.models.ForeignKey.on_delete

You have it pointed here:

PROTECT[source] Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

Remove the on_delete=models.PROTECT on your user field. And run manage.py makemigrations

ForeignKey fields have a default value of CASCADE for the on_delete argument. This means that deleting the user object will cascade down and also delete the userinfo object linked to that user.

Looks like this is the behaviour you are looking for.

You can read more about this in the documentation documentation

Also note although on_delete has a default value fo CASCADE this argument will be required from Django 2.0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM