dsalaj
dsalaj

Reputation: 3247

Django: How to make admin not delete the relative objects?

When deleting an object in admin interface, I want to prevent removal of related objects.

class ObjectToDelete(models.Model):
    timestamp = models.DateTimeField()

class RelatedObject(models.Model):
    otd = models.ForeignKey('app.ObjectToDelete', null=True, blank=True)

Since the ForeignKey in RelatedObject is nullable, I should be able to set it to None instead of deleting the whole object. And this is exactly the behaviour I want to have.

I know that I can create custom delete actions for this admin interface.

And I am also aware that I could make ManyToManyField in ObjectToDelete which would also prevent removal of RelatedObject. But then I wouldn't have the one-to-many relation which I want.

Is there a simple way of achieving this?

Upvotes: 0

Views: 922

Answers (1)

Muhammad Shoaib
Muhammad Shoaib

Reputation: 372

Set the on_delete option for your foreign key. If you you want to set the value to None when the related object is deleted, use SET_NULL:

models.ForeignKey('app.ObjectToDelete', on_delete=models.SET_NULL)

These rules apply however you delete an object, whether you do it in the admin panel or working directly with the Model instance. (But it won't take effect if you work directly with the underlying database in SQL.)

Upvotes: 1

Related Questions