Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django delete without calling signals

I use signals for things that should always be done when an object is deleted, saved, updated, etc. However, there are times when I don't want to call my save signals, so I use

Model.objects.filter(id=instance.id).update(field=value)

instead of the instance's save method:

instance.save()

In the case of deleting objects, there are also times when I don't want to call the delete signals, but I haven't found a way to avoid calling them. Is there a way??

UPDATE:

I'm using django 1.6.2 and calling the delete method like this:

Model.objects.filter(id=instance.id).delete()

on the queryset still still calls the delete signal.

like image 822
tzenderman Avatar asked Nov 15 '25 21:11

tzenderman


2 Answers

There is unsafe and undocumented way which probably can change between versions and also can lead to unexpected consequences which will be hard to debug.

This is a hack that probably you don't want to use but.... it's possible.

qs = Model.objects.filter(id=instance.id)
qs.order_by().select_related(None)._raw_delete(qs.db)

If you have any related objects to this one it will probably fail with database error because records will not be deleted automatically by Django

like image 65
VStoykov Avatar answered Nov 18 '25 13:11

VStoykov


In the place where you don't want signals to be called, you have to disconnect them, run you code and then reconnect them again. You can take a look on how mute_signal decorator is implemented in FactoryBoy or just use (but it's basically intended for django tests)

like image 35
Mounir Avatar answered Nov 18 '25 14:11

Mounir