djangodjango-signals

Can you tell why here create two objects instead of one object of Notification?


Here I would like to create a notification after creating a blog. It's working fine, but the issue is here creating two objects of Notification instead of one object. Can you tell me where is the problem in my code?

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"
    )

Solution

  • I solve this way:

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

    Note: if have any alternative better solution just give me.