简体   繁体   English

Django:断开 post_save 信号以避免递归

[英]Django: disconnect a post_save signal to avoid recursion

This is my model:这是我的 model:

class Paper(models.Model):
    ...
    collection = models.ForeignKey(Collection, on_delete=models.CASCADE)
    rang = models.IntegerField(default=0)
    class Meta:
        ordering = ['collection','rang']

When saving the model, I want it to update all the 'rang' fields in each object of the model so that they increase by 10.保存 model 时,我希望它更新 model 的每个 object 中的所有“rang”字段,以便它们增加 10。

I use the post_save signal below to avoid a problem of recursion:我使用下面的 post_save 信号来避免递归问题:

@receiver(post_save, sender=Papier)
def redifine_rang(sender, *args,  **kwargs):
    for idx, paper in enumerate(Paper.objects.filter(collection = kwargs['instance'].collection)):
        paper.rang = idx*10
        Signal.disconnect(post_save, sender=Papier)
        paper.save()
        Signal.connect(post_save, sender=Papier)

However, I can't get the signal to disconnect and connect.但是,我无法获得断开连接和连接的信号。 Does anyone have any recommendations?有人有什么建议吗?

you can just use update你可以只使用update

Paper.objects.filter(pk=paper.pk).update(rang=idx*10)

instead of而不是

paper.rang = idx*10
Signal.disconnect(post_save, sender=Papier)
paper.save()
Signal.connect(post_save, sender=Papier)

A little clarification about the way to disable particular post_save signal.关于禁用特定post_save信号的方法的一些说明。 This way:这样:

Signal.disconnect(post_save, sender=Papier)

is didn't work for Django 2.2.不适用于 Django 2.2。

The working option of turning off the signal will look like:关闭信号的工作选项如下所示:

from django.db.models.signals import post_save
from django.dispatch import Signal


Signal.disconnect(post_save, receiver=redifine_range, sender=Papier)

It doesn't work for Django 4.0.它不适用于 Django 4.0。

Now you need to disable a certain handler for the signal.现在您需要为信号禁用某个处理程序。

post_save.disconnect(your_handler, sender=Papier)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM