addHow使django post_save信号仅在创建期间运行

时间:2017-01-08 13:54:59

标签: python django signals

我在我的项目中使用django-notifications,我想在使用信号创建模型时通知特定用户,但post_save也会在更新模型时运行,如何防止这种情况并且仅post_save方法在创建模型时运行。

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)    

我尝试使用if instance.pk是None,但是当我添加这个条件时它根本不运行。

已编辑:代码检查是否已创建

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

1 个答案:

答案 0 :(得分:6)

有一个创建的命名参数,如果它是一个新对象,将设置为True。

看看这里 - 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