addHow to make django post_save signal run only du

2019-04-28 23:16发布

问题:

I'm using django-notifications in my project and I want to notify a particular user whenever a model is created using the signal, but the post_save also runs when a model is being updated how do I prevent this and only make the post_save method run when a model is created.

models.py

class Card(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    list = models.ForeignKey(List, related_name='cards')
    story_points = models.IntegerField(null=True, blank=True)
    business_value = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return "Card: {}".format(self.title)

def my_handler(sender, instance, **kwargs):
    if instance.pk is None:
        notify.send(instance.user, recipient=User.objects.get(pk=1),   target=instance, verb='created')  

post_save.connect(my_handler, sender=Card)    

I tried using if instance.pk is None, but when I add this condition it doesn't run at all.

EDITED: The code checking if created

def my_handler(sender, instance, created, **kwargs):
    if created:
        notify.send(instance.user, recipient=User.objects.get(pk=1), target=instance, verb='created')  

回答1:

There is a created named argument which will be set to True if it's a new object.

Have a look here - https://docs.djangoproject.com/en/1.10/ref/signals/#post-save

def my_func(sender, instance, created, **kwargs):
    print("Created: ", created)

class MyModel(models.Model):
    x = models.CharField(max_length=255)

post_save.connect(my_func, sender=MyModel)

>>> MyModel.objects.create(f='asdf')
Created:  True
>>> m = MyModel.objects.all().first()
>>> m.x
'asdf'
>>> m.x = 'a'
>>> m.save()
Created:  False