notification.users.set(instance.user.all()) is not doing anything while creating model instance in django

23 Views Asked by At

The Notification Model I have:

class Notification(models.Model):
    users = models.ManyToManyField(User)
    notification_time = models.DateTimeField(auto_now_add=True)
    type = models.CharField(max_length=255)
    message = models.TextField()

    def __str__(self):
        return self.type

while new Assignment is created I want to send notification to all those who are included in the assignment. But while working through signals, it didn't cteate new users. The signals code is:

@receiver(post_save,sender=Assignment)
def assignment_post_save(sender,instance,created,**kwargs):
    if created:
        notification = Notification.objects.create(
            type='Assignment',
            message=instance.title
        )
        notification.users.set(instance.user.all())
        

type and message have value passed and worked perfectly. found issue only on user.

I want notification instance is created with user's data on it.

1

There are 1 best solutions below

1
Dori On

You should override the save method of the Notification model, rather than using signals

class Notification(models.Model):
    users = models.ManyToManyField(User)
    notification_time = models.DateTimeField(auto_now_add=True)
    type = models.CharField(max_length=255)
    message = models.TextField()

    def __str__(self):
        return self.type

    def save(self, *args, **kwargs):
        super(Notification, self).save(*args, **kwargs)
        
        if self.pk is None:
            for user in self.users.all():
                user.notification_set.add(self)

The save method will automatically add the notification to the corresponding user's notification_set. You don't need the signal anymore. Instead, you can create a new Notification instance and add the users directly to it.