Django信号仅用于新条目。

时间:2021-03-22 00:12:35

I'm using Django's post_save signal to send emails to users whenever a new article is added to the site. However, users still receive new emails whenever I use save() method for already created articles. How is it possible to receive emails only when NEW entry was added?

我使用Django的post_save信号向用户发送电子邮件,每当向站点添加新文章时。但是,当我为已经创建的文章使用save()方法时,用户仍然会收到新的电子邮件。只有在添加新条目时才可以接收电子邮件?

Thanks in advance

谢谢提前

3 个解决方案

#1


28  

The post_save signal receives a boolean created argument which indicates if the saved instance was created.

post_save信号接收一个布尔创建的参数,该参数指示是否创建了已保存的实例。

def my_callback(sender, **kwargs):
    if kwargs['created']:
        print('Instance is new')

#2


2  

Take a look at https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save

看一下https://docs.djangoproject.com/en/dev/ref/signals/#django.db. signals.post_save。

There actually is an argument passed with the signal "created: A boolean; True if a new record was created".

实际上有一个参数通过“创建:布尔值;如果创造了一个新的记录。

I think, that should do the trick.

我想,这应该能达到目的。

#3


0  

Checking for instance.id is a nice way of determining if the instance is "new". This only works if you use ids that are auto-generated by your database.

检查实例。id是确定实例是否是“新”的好方法。只有在使用由数据库自动生成的id时,这才有效。

#1


28  

The post_save signal receives a boolean created argument which indicates if the saved instance was created.

post_save信号接收一个布尔创建的参数,该参数指示是否创建了已保存的实例。

def my_callback(sender, **kwargs):
    if kwargs['created']:
        print('Instance is new')

#2


2  

Take a look at https://docs.djangoproject.com/en/dev/ref/signals/#django.db.models.signals.post_save

看一下https://docs.djangoproject.com/en/dev/ref/signals/#django.db. signals.post_save。

There actually is an argument passed with the signal "created: A boolean; True if a new record was created".

实际上有一个参数通过“创建:布尔值;如果创造了一个新的记录。

I think, that should do the trick.

我想,这应该能达到目的。

#3


0  

Checking for instance.id is a nice way of determining if the instance is "new". This only works if you use ids that are auto-generated by your database.

检查实例。id是确定实例是否是“新”的好方法。只有在使用由数据库自动生成的id时,这才有效。