pythondjangoforeign-key-relationship

Deleting auto created model which is under PROTECTED ForeignKey


class Basket:
    name = models.CharField(max_length=50, blank=True, null=True)

class Apple:
    name = models.CharField(max_length=50, blank=True, null=True)
    basket = models.ForeignKey(Basket, on_delete=models.PROTECT)

...

myapple = new Apple(name="my")
myapple.save()

...

auto_created_basket = myapple.basket
myapple.basket = existing_basket
auto_created_basket.delete()

I try to swap out the auto_created_basket to another one, but I get an error when I try to delete it.

"Cannot delete some instances of model 'Basket' because they are referenced through a protected foreign key: 'Apple.basket'", [<Apple: My apple>])


Solution

  • I hate to answer my question, but my example was too over simplified. The answers are very good points.

    In the real product there are post_save signals involved, responsible for the creation of the auto_created_basket for example.

    The problem is that when I say myapple.basket = existing_basket Django's layer is fine, but the DB is still holding the reference to older relation. The solution in my case was to move the auto_created_basket.delete() after I save myapple once more.