from django.db.models.signals import post_save
from django.dispatch import receiver
class Connector(models.Model):
connector_id = models.AutoField(primary_key = True)
name = models.CharField(max_length=255, null=False,unique=True)
description = models.TextField(null=True)
class ConnectorAud(models.Model):
id = models.AutoField(primary_key = True)
ref_connector_id = models.CharField(max_length=255, null=False)
name = models.CharField(max_length=255, null=False,unique=True)
description = models.TextField(null=True)
@receiver(post_save, sender=Connector)
def create_connector_audit_trail(sender, **kwargs):
connector = ConnectorAud(
ref_connector_id = kwargs.get('connector_id'),
name = kwargs.get('name'),
description = kwargs.get('description',''),
)
connector.save()
这会导致Connector()在运行connector.save()时运行两次
如何解决这个问题?
答案 0 :(得分:0)
首先,您应该为dispatch_uid
装饰器添加具有唯一名称的@receiver
,以避免重复信号(例如,当您多次导入带有信号的文件时,如果唯一{{1,则会多次注册信号不存在)。
每次保存模型时都会调用接收器,如果要在第一次创建连接器时只创建一次dispatch_uid
,则应将ConnectorAud
param添加到接收器方法中,如下所示:< / p>
created
有了这个,当您编辑并保存@receiver(post_save, sender=Connector,
dispatch_uid='create_connector_audit_trail')
def create_connector_audit_trail(sender, instance, created, **kwargs):
if created:
ConnectorAud.objects.create(ref_connector_id=instance.pk,
name=instance.name,
description=instance.description)
时,将不会多次创建Connector
。