How to save a model without sending a signal?

2020-05-29 22:17发布

How can I save a model, such that signals arent sent. (post_save and pre_save)

5条回答
狗以群分
2楼-- · 2020-05-29 22:39

This ticket has been marked as "wontfix" because:

In short, it sounds like, given the defined purpose of signals, it is the attached signal handler that needs to become more intelligent (like in davedash's suggestion), rather than the code that emits the signal. Disabling signals is just a quick fix that will work when you know exactly what handlers are attached to a signal, and it hides the underlying problem by putting the fix in the wrong place.

查看更多
家丑人穷心不美
3楼-- · 2020-05-29 22:48

It's a bit of a hack, but you can do something like this:

use a unique identifier with a filter and then use the update method of the queryset (which does not trigger the signals)

user_id = 142187
User.objects.filter(id=user_id).update(name='tom')
查看更多
该账号已被封号
4楼-- · 2020-05-29 22:49
ModelName.objects.bulk_create([your object/objects])

also you can read more here django docs

查看更多
家丑人穷心不美
5楼-- · 2020-05-29 22:51

If you have mutual relations on models and their signals still you can decouple signal's logic to have more signals of same type, and handle your logic in more sophisticated way:

You can check in signals, the state of object:

kwargs['created']

You can check the state of any pasted extra value: So in one signal, you will read at first:

if `kwargs['instance'].skip_signals`:
   return

and in another place, before save() you will just set that skip_signals on the specific object, in specific situation. (there is no need to define it as model field)

You can also do not emit signals:

  • by overriding method(s) on models,
  • or by adding own save_without_signals(),
  • or just as mentioned already, doing filter(pk=<>).update(...)
查看更多
淡お忘
6楼-- · 2020-05-29 22:56

There is currently a ticket pending a Django design decision for this feature.

Included in the ticket is a diff for a patch with the proposed implementation.

查看更多
登录 后发表回答