2

I have the Model where i have relations with 3 diff models.

Now i know that if i use object.delete() , then child objects will also gets deleted.

Now the problem is that in my whole models classes i have the database column called DELETED which i want to set to 1 whenever someone deletes some object.

I can override the deleted function in class called BaseModel and and override the custom delete method of updating field to 1. But the problem is

If i do that way then i have to manually go through all the cascading relationships and manually call the delete ob every object.

Is there any way that by just calling object.delete(). It automatically traverses through child objects as well

Mirage
  • 30,868
  • 62
  • 166
  • 261
  • 1
    Have a look here https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.on_delete. Especially the SET() option. – Paulo Oct 22 '12 at 03:30
  • @Paulo You should probably post that as an answer – jsvk Oct 22 '12 at 03:50
  • @paulo , i read that doc but that is only for ForeignKey , i am looking for manytomany relationship. Also i am not able to fully understood. how can i deleted my child object with SET function – Mirage Oct 22 '12 at 03:57
  • Just a note of causion with `delete()` is that it is not called when deleting objects using queryset like `Model.objects.filter(...).delete()`. In that case you have to use `post_delete` signal. – miki725 Oct 22 '12 at 03:57

1 Answers1

0

Please look at Django: How can I find which of my models refer to a model.

You can use a Collector to get all references to all the necessary items using collect(). This is the code Django is using to simulate the CASCADE behavior. Once you have collected all the references, for each of those items you can update the DELETED column.

More info in the code.

Good luck.

Community
  • 1
  • 1
dnozay
  • 23,846
  • 6
  • 82
  • 104