2

Let's say I have this model:

class UserBook(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
    book = models.ForeignKey(Book, on_delete=models.PROTECT)

Where the user is only allowed to borrow 1 book at a time. I want instances of this model to get deleted if the user gets deleted, but I don't want them to get deleted if a book gets deleted (by mistake, just a precaution).

What is the expected behaviour when a user gets deleted using the above constraint? I'm getting:

Cannot delete some instances of model 'UserBook' because they are referenced through a protected foreign key

Is there a way to achieve what I want? I tried to delete UserBook on pre_save/post_save signals with the User as a sender but neither worked.

mota
  • 5,275
  • 5
  • 34
  • 44

1 Answers1

2

What you are trying to achieve is done through RESTRICT option.

Here is an example from the official docs

They also use models.ForeignKey and not models.OneToOne

This post may also be helpful https://stackoverflow.com/a/38389488/13482680

periwinkle
  • 386
  • 3
  • 9
  • `RESTRICT` indeed solves this. Unfortunately it's fairly new (>= 3.1) so can't use it without an upgrade. Thanks! – mota Mar 17 '21 at 08:40
  • 1
    I used the opportunity to upgrade Django and this is now working perfectly as I wanted. Thanks again! – mota Mar 17 '21 at 10:10