You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建Blog后重复生成两个Notification对象的问题排查求助

问题排查:创建Blog后重复生成两条Notification通知

创建Blog后本应生成一条Notification通知,但实际会生成两条,以下是代码和排查方案:

现有代码

models.py

class blog(models.Model):
    title = models.CharField(max_length=250)
    img = models.ImageField(upload_to="img_file/", blank=True, null=True)

    def __str__(self):
        return f"{self.pk}.{self.title}"


class Notification(models.Model):
    title = models.CharField(max_length=250)
    details = models.TextField()
    is_seen = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.pk}.{self.title}"

signal.py

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

from .models import blog, Notification

@receiver(post_save, sender=blog)
def call_notification(sender, instance, **kwargs):
    Notification.objects.create(
        title="New Blog Post uploaded", details=f"{instance.id} number Blog"
    )

问题原因及解决方案

核心原因

最常见的情况是信号被重复注册:比如开发模式下Django自动重载代码,导致signal.py被多次导入,同一个信号处理器被注册多次,每次触发post_save时就会执行多次。另外,也可能是代码中对Blog对象执行了两次save()操作,触发两次post_save信号。

解决方案

方案1:仅在创建Blog时生成通知

修改信号处理函数,通过created参数判断是否是新创建的对象,只在创建时执行逻辑(同时避免后续更新Blog时误触发):

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

from .models import blog, Notification

@receiver(post_save, sender=blog)
def call_notification(sender, instance, created, **kwargs):
    if created:  # 仅当对象是新创建时执行
        Notification.objects.create(
            title="New Blog Post uploaded", details=f"{instance.id} number Blog"
        )

方案2:确保信号只注册一次

通过应用配置类的ready()方法导入信号,避免重复注册:

  1. 修改应用目录下的apps.py:
from django.apps import AppConfig

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'your_app_name'  # 替换为你的应用名称

    def ready(self):
        # 在这里导入信号模块,确保只在应用启动时注册一次
        import your_app_name.signals
  1. 在项目settings.py的INSTALLED_APPS中,替换原来的应用名称为配置类路径:
INSTALLED_APPS = [
    # ...其他应用
    'your_app_name.apps.YourAppConfig',  # 替换为你的配置类路径
]

这两个方案结合使用,既能避免重复注册的问题,也能防止更新操作误触发通知,彻底解决重复生成Notification的问题。

内容的提问来源于stack exchange,提问作者Mossaddak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 06:55:16